2016-09-12 18 views
-4

特定のテキストを含む行をファイルから検索し、その行全体を新しい行に置き換えようとしています。文字列を含む行をPythonに置き換えてください

は、私が使用しようとしている:

pattern = "Hello" 
file = open('C:/rtemp/output.txt','w') 

for line in file: 
    if pattern in line: 
     line = "Hi\n" 
     file.write(line) 

私はというエラーを取得:

io.UnsupportedOperation: not readable 

私は私が間違ってやっているかわからないんだけどを、誰かが助けることができますしてください。

+1

http://stackoverflow.com/questions/39086/search-and-replace-aファイル内のファイル中の行またはファイルhttp://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file-using-python – MooingRawr

+4

あなたは書き込み専用にファイルを開きます。両方を行うには、これを行う必要があります:http://stackoverflow.com/questions/6648493/open-file-for-both-reading-and-writing – Andy

答えて

2

「w」でファイルを開いたとします。これは、書き込みを行うことを意味します。それからあなたはそれから読むことを試みる。だからエラー。

そのファイルから読み込み、出力を書き込むために別のファイルを開きます。必要に応じて、完了したら、最初のファイルを削除し、出力(temp)ファイルの名前を最初のファイルの名前に変更します。

+0

ありがとう、それはそれを解決しました – ChrisG29

0

あなたのpythonのために非常に新しいなければなりません^ _^

あなたはこのようにそれを書き込むことができます。

pattern = "Hello" 
file = open(r'C:\rtemp\output.txt','r') # open file handle for read 
# use r'', you don't need to replace '\' with '/' 
result = open(r'C:\rtemp\output.txt', 'w') # open file handle for write 

for line in file: 
    line = line.strip('\r\n') # it's always a good behave to strip what you read from files 
    if pattern in line: 
     line = "Hi" # if match, replace line 
    result.write(line + '\n') # write every line 

file.close() # don't forget to close file handle 
result.close() 
関連する問題