2015-07-13 82 views
0

我想打开一个txt文件并将所有“hello”替换为“love”并保存,并且不要创建一个新文件。只需修改同一个txt文件中的内容即可。python打开一个文件并替换内容

我的代码只是在“你好”之后添加“爱”,而不是替代它们。

任何方法可以解决它?

THX这么多

f = open("1.txt",'r+') 
con = f.read() 
f.write(re.sub(r'hello','Love',con)) 
f.close() 
+1

http://stackoverflow.com/questions/2424000/read-and-overwrite-a-file-in-python – Blorgbeard

+1

也许这有你的问题的答案[如何使用Python搜索和替换文件中的文本?](http://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file- using-python) – GAVD

回答

0

在阅读文件,文件指针是在文件的结尾;如果你写的话,你会追加到文件的末尾。你要像

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 
+2

不应该是'f = open('1.txt','r +')'? –

+0

@ KhalilAmmour-خليلعمور是的。 – Luke

+0

非常感谢。它现在的作品:) – Luke

0

您可以创建一个新的文件,并替换您在第一次找到所有的话,他们在第二记录。见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") 
+0

所有这一切,直到你必须用较长的一个替换一个较小的单词。在这种情况下,您必须在内存中执行此操作,或者使用mmap模块在运行时更改文件大小,在新位置移动字符并插入所需内容。对于其他情况,seek()tell()和truncate()会有所帮助。 – Dalen

+0

Aha,是的,要清楚的是,您可以在不使用mmap的情况下将您的文件内容移动到正确的位置,但这会更有效地杀死您和操作系统。 mmap允许您将RAM或磁盘内存用作可变字符串。 – Dalen