如何替换文本文件中的一行文本(python) [英] How do you replace a line of text in a text file (python)
本文介绍了如何替换文本文件中的一行文本(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,如下所示:
I have a text file that looks like this:
unknown value 1
unknown value 2
unknown value 3
unknown value 4
unknown value 5
如何选择一行并将其内容替换为另一个字符串?
How can I choose a line and replace its contents with another string?
例如:
将unknown value 1
更改为unknown value 0
.
我该怎么做?
推荐答案
import fileinput
for line in fileinput.input('inFile.txt', inplace=True):
print line.rstrip().replace('oldLine', 'newLine'),
这会将所有行替换为文本'oldLine'
,如果您只想替换第一行,则需要添加条件并退出循环.
This replaces all lines with the text 'oldLine'
, if you want to replace only the first one then you need to add a condition and break out of the loop.
添加rstrip()可避免在每行之后添加多余的空间
Adding rstrip() avoids adding an extra space after each line
这篇关于如何替换文本文件中的一行文本(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文