且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

搜索单词,并使用 fileinput 在 Python 中的文件中替换包含该单词的整行

更新时间:2023-11-28 19:17:40

我意识到我错了,只是缩进了.在问题中提到的代码段 1 中,如果我从 if 的范围内带来打印线",即如果我将其缩小,那么就解决了...

I realized that I was wrong by just an indentation. In the code piece 1 mentioned in the question, if I am bringing the 'print line,' from the scope of if i.e. if i outdent it, then this is solved...

由于这一行在 if 的范围内,因此只有这行 new_text 被写入文件,其他行没有被写入,因此文件只剩下 new_text.所以,代码片段应该如下:-

As this line was inside the scope of if, hence, only this new_text was being written to the file, and other lines were not being written, and hence the file was left with only the new_text. So, the code piece should be as follow :-

text = "mov9 = "   # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
    if text in line:
        line = new_text
    print line,
x.close()

另外,萨克森的罗尔夫 &Padraic Cunningham 有点相似.

Also, the second solution given by Rolf of Saxony & the first solution by Padraic Cunningham is somehow similar.