我只是简单地遍历一个外部文件(其中包含一个短语),并想看看是否存在一行(其中包含‘爸爸’这个词),如果我找到它,我想用‘妈妈’替换它。这是我建立的程序..。但我不知道它为什么不起作用!
message_file = open('test.txt','w')
message_file.write('Where\n')
message_file.write('is\n')
message_file.write('Dad\n')
message_file.close()
message_temp_file = open('testTEMP.txt','w')
message_file = open('test.txt','r')
for line in message_file:
    if line == 'Dad':  # look for the word
        message_temp_file.write('Mum')  # replace it with mum in temp file
    else:
        message_temp_file.write(line)  # else, just write the word
message_file.close()
message_temp_file.close()
import os
os.remove('test.txt')
os.rename('testTEMP.txt','test.txt')这应该很简单.这让我很生气!谢谢。
发布于 2014-03-18 17:33:20
您没有任何行是"Dad"。您有一行是"Dad\n",但没有"Dad"。此外,由于您已经完成了message_file.read(),光标位于文件的末尾,因此for line in message_file将立即返回StopIteration。您应该在message_file.seek(0)循环之前执行for。
print(message_file.read())
message_file.seek(0)
for line in message_file:
    if line.strip() == "Dad":
        ...这应该把光标放回文件的开头,去掉换行符,得到你需要的东西。
请注意,这个练习是一个很好的例子,说明了如何在一般情况下不做事情!更好的执行办法是:
in_ = message_file.read()
out = in_.replace("Dad","Mum")
message_temp_file.write(out)https://stackoverflow.com/questions/22486738
复制相似问题