0

すべての行を読み取る代わりに、ファイル内の文字列を検索して置き換えるだけではいけません...私は試していますが、どうすればよいかわかりませんか?

file = open(C:\\path.txt,"r+")
lines = file.readlines()
replaceDone=0
file.seek(0)
newString="set:: windows32\n"
for l in lines: 
     if (re.search("(address_num)",l,re.I) replaceDone==0:
        try:
            file.write(l.replace(l,newString))
            replaceDone=1
        except IOError:
             file.close()
4

2 に答える 2

0

ファイルの '(address_num)' のすべてのシーケンスを 'set:: windows32' に置き換える、適応できる例を次に示します。

import fileinput
import re

for line in fileinput.input('/home/jon/data.txt', inplace=True):
    print re.sub('address_num', 'set:: windows32', line, flags=re.I),
于 2013-02-26T04:04:37.637 に答える
0

これはあまりメモリ効率が良くありませんが、あなたが探しているものだと思います:

import re
text = open(file_path, 'r').read()
open(file_path, 'w').write(re.sub(old_string, new_string, text))

ファイル全体を読み取り、ファイル全体を置き換えて書き戻します。

于 2013-02-26T04:42:54.257 に答える