所以我想要读完一个文件,检查每一行,看看它是否包含我要查找的字符串的一部分。一旦我找到了正确的行,我就想在文件中重写该行。
这是我到目前为止所知道的:
f = open("playlist.py", "r+")
for line in f:
if old in line:
f.write(" " + str(item) + ":" + " " +
"\"" + new_text + "\"")
f.close()
break
f.close()这段代码找到了正确的行,但是写到了文件的末尾。我认为读和写iter应该是共享的,但我猜不是:(
发布于 2014-04-05 13:10:36
使用fileinput
import fileinput
for line in fileinput.input("test.txt", inplace=True):
if contains_str_youlookingfor:
print "what_you_want_to_rewire"
else:
print line.rstrip()
fileinput.close()如果你使用的是Python 3.2+,最好使用上下文管理器:
with fileinput.input("test.txt", inplace=True) as f:
for line in f:
if contains_str_youlookingfor:
print("what_you_want_to_rewire")
else:
print(line, end='')这些行将被"what_you_want_to_rewire"替换,并且不会创建任何新文件。
编辑
如果不删除原始换行符或在不换行符的情况下打印,则会得到额外的空行。
发布于 2014-04-05 09:21:49
您是否可以使用r+模式打开文件,然后将内容读取到列表中,并替换包含所需数据的行(列表项),然后将整个文件写回仍处于打开状态的文件?像这样的东西
f=open(filename, 'r+')
data=f.readlines()
for line in data:
if old in line:
line=" " + str(item) + ":" + " " +
"\"" + new_text + "\""
f.truncate()
f.writelines(data)
f.close()https://stackoverflow.com/questions/22874858
复制相似问题