我想打开一个txt文件并将所有“hello”替换为“love”并保存,并且不要创建一个新文件。只需修改同一个txt文件中的内容即可。python打开一个文件并替换内容
我的代码只是在“你好”之后添加“爱”,而不是替代它们。
任何方法可以解决它?
THX这么多
f = open("1.txt",'r+')
con = f.read()
f.write(re.sub(r'hello','Love',con))
f.close()
我想打开一个txt文件并将所有“hello”替换为“love”并保存,并且不要创建一个新文件。只需修改同一个txt文件中的内容即可。python打开一个文件并替换内容
我的代码只是在“你好”之后添加“爱”,而不是替代它们。
任何方法可以解决它?
THX这么多
f = open("1.txt",'r+')
con = f.read()
f.write(re.sub(r'hello','Love',con))
f.close()
在阅读文件,文件指针是在文件的结尾;如果你写的话,你会追加到文件的末尾。你要像
f = open("1.txt", "r") # open; file pointer at start
con = f.read() # read; file pointer at end
f.seek(0) # rewind; file pointer at start
f.write(...) # write; file pointer somewhere else
f.truncate() # cut file off in case we didn't overwrite enough
您可以创建一个新的文件,并替换您在第一次找到所有的话,他们在第二记录。见How to search and replace text in a file using Python?
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()
或者,你可以使用fileinput
import fileinput
for line in fileinput.FileInput("file",inplace=1):
line = line.replace("hello","love")
http://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python – Blorgbeard
也许这有你的问题的答案[如何使用Python搜索和替换文件中的文本?](http://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file- using-python) – GAVD