如何使用 Python 在文本文件中查找和替换?\\
pythonserver side programmingprogramming更新于 2025/7/7 11:24:17
以下代码在给定的文本文件中进行替换。
替换后,文本将写入新文本文件"bar.txt"
示例
f1 = open('foo.txt', 'r')
f2 = open('bar.txt', 'w')
for line in f1:
print line
f2.write(line.replace('Poetry', 'Prose'))
f2 = open('bar.txt', 'r')
for line in f2:
print line,
f1.close()
f2.close()
输出
这给出了输出
Poetry is often considered the oldest form of literature. Poetry today is usually written down, but is still sometimes performed. Prose is often considered the oldest form of literature. Prose today is usually written down, but is still sometimes performed.
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

