如何使用python在文件中搜索一个字符串(比如str1)并将其替换为另一个字符串(比如str2)



我必须在文件中搜索一个字符串(比如str1),然后用同一个文件中的另一个字符串(比如str2)替换它。2 个字符串的搜索(str1)和写入(str2)将在同一文件上完成。请有人为此建议一些方法或逻辑。

以下代码将执行该任务:

FILE = r'A:somesortoffloppyfile.txt' # The target file.
str1 = 'n'
str2 = 'rn'
data = ''
with open(FILE) as f: # Comment the "with" block under Python 2.6
    data = f.read()
# Uncomment lines below if the "with" statement is commented
##f = open(FILE)
##data = f.read()
##f.close()
data = data.replace(str1, str2)
with open(FILE, 'w') as f: # Same as for previous "with"
    f.write(data)
# And here too
##f = open(FILE)
##f.write(data)
##f.close()

相关内容

最新更新