为什么这个简单的搜索不起作用?

Tin*_*iny 2 python

我只是迭代一个外部文件(包含一个短语),并想看看是否存在一条线(其中有"爸爸"一词)如果我找到它,我想用"妈妈"替换它.这是我建立的程序......但我不确定它为什么不起作用?!

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')
Run Code Online (Sandbox Code Playgroud)

这应该是这么简单......这让我生气!谢谢.

Ada*_*ith 5

你没有任何行"Dad".你有一条线"Dad\n",但没有"Dad".此外,由于您已经完成message_file.read(),光标位于文件的末尾,因此for line in message_fileStopIteration立即返回.你应该message_file.seek(0)在你的for循环之前做.

print(message_file.read())
message_file.seek(0)
for line in message_file:
    if line.strip() == "Dad":
        ...
Run Code Online (Sandbox Code Playgroud)

这应该将光标放回文件的开头,并删除换行符并获得所需内容.

请注意,此练习是一般情况下如何不做事的一个很好的例子!更好的实施将是:

in_ = message_file.read()
out = in_.replace("Dad","Mum")
message_temp_file.write(out)
Run Code Online (Sandbox Code Playgroud)