2016-07-11 11 views
-1

STR1を検索し、STR2を含む行全体を置き換える必要があるファイルがあります。たとえばfile1は、以下のデータPython:行内のSTR1を検索し、行全体をSTR2に置き換えます。

Name: John 
Height: 6.0 
Weight: 190 
Eyes: Blue 

が含まれている私は、上記のファイルにNameを検索し、その後​​と行全体を交換する必要があります。私はこれを簡単にsedで達成することができます

sed -i 's/.*Name.*/Name:Robert/' file1 

しかし、どのようにPythonで同じを取得します。行全体を置き換えるために上記のコードを変更する方法

#! /usr/bin/python 
import fileinput 
for line in fileinput.input("file1", inplace=True): 
    # inside this loop the STDOUT will be redirected to the file 
    # the comma after each print statement is needed to avoid double line breaks 
    print line.replace("Name: John", "Name: Robert"), 

を、例えば以下のように私はfileinputを使用して別の文字列で1つの文字列を置き換えることができ、'*'を使用しても、検索条件(if "Name" in line)でファイル内のすべての行を置き換えます

+0

どのように上記のコードはあなたが望むことをしませんし、* '' * 'を使って*ファイル内のすべての行を*置き換えることはどういう意味ですか? –

+0

'import re; line = re.sub( '。* Name。* /'、 'Name:Robert'、line) '? –

+0

'Name:John'の代わりに' Name'という文字列を検索として使い、 'John'prioriという値がわからないので、行全体を置き換えたいと思います。 '*'はファイル全体を 'Name:Robert'という文字列で置き換えます。 – WanderingMind

答えて

1

string.find()を使用して、文字列が別の文字列内にあるかどうかを判断できます。 Related Python docs

#! /usr/bin/python 
import fileinput 
for line in fileinput.input("file1", inplace=True): 
    if line.find("Name:") >= 0: 
     print "Name: Robert" 
    else: 
     print line[:-1] 
+0

OPはすでに "if"の名前を "行内に"知っていて、彼はまだ問題があるので、 'find'はそれ以上に良いとは思えません。 – Kevin

+0

[: - 1]行がトリックをしました。しかし、なぜ ':'?私は最後のエントリに '[-1]'でアクセスすることができると思った。 – WanderingMind

+0

'[-1]'を使うと最後の文字にアクセスし、コロンでスプライスに変換したので、今度は0番目のインデックスから最後のインデックスから1を引いたものです。 –

1

正確に何をしてください。

def replace_basic(key_to_replace, new_value, file): 
    f = open(file, 'rb').readlines() 
    with open(file, 'wb') as out: 
     for line in f: 
      if key_to_replace in line: 
       out.write(new_value+'/n') #asuming that your format never changes then uncomment the next line and comment out this one. 
       #out.write('{}: {}'.format(key_to_replace, new_value)) 
       continue 
      out.write(line) 
+0

あなたは 'out.write(new_value + '\ n')'を意味すると思います。それは示唆どおりに機能します。この方法で元のファイルをバックアップする方法はありますか? – WanderingMind

関連する問題