如何使用 Python 在文本文件中查找和替换?\n\n\n


以下代码将替换给定的文本文件中的内容。 

替换之后,文本将写入新的文本文件 '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.

更新时间: 19-Feb-2020

380 次浏览

开启你的职业生涯

通过完成课程获得认证

立刻注册
广告
© . All rights reserved.