gpt4 book ai didi

python - 替换Python 3中的文本但它只读取一行

转载 作者:行者123 更新时间:2023-11-28 21:37:13 25 4
gpt4 key购买 nike

我正在尝试在 Python 3 中使用文件进行搜索和替换

但是当我尝试我的代码时,它仅在第一行有效,并且不会遍历每一行并替换它。

到目前为止我正在尝试

f1 = open('test.txt', 'r')
f2 = open('test2.txt', 'w')
for line in f1:
f1.readlines()
find = (input('Enter word to find: '))
while find in line:
print('Word Found')
replace = input('Enter Word to replace with: ')
replace_action = (input('Are you sure you want to replace Y or N:'))
if replace_action.lower() == 'y':
f2.write(line.replace(find.lower(), replace))
else:
print('You have cancelled this operation')
else:
print('Word not found in file')
f1.close()
f2.close()

此代码仅读取第一行,但无法进一步工作。

最佳答案

发生这种情况是因为您没有正确读取文件。

for line in f1:
f1.readlines()

f1.readlines() 消耗所有返回字符串列表的文件行。
您只需删除 f1.readlines() 行即可。

如果您想了解在 python 中读取文件的各种方法,请查看文档。 https://docs.python.org/2.7/tutorial/inputoutput.html
https://docs.python.org/3/tutorial/inputoutput.html

关于python - 替换Python 3中的文本但它只读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com