你如何替换文本文件中的一行文本(python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16622754/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you replace a line of text in a text file (python)
提问by user2396472
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?
如何选择一行并将其内容替换为另一个字符串?
For example:
例如:
Change unknown value 1to unknown value 0.
更改unknown value 1为unknown value 0。
How can I accomplish this?
我怎样才能做到这一点?
回答by oleg
Try this
尝试这个
with open('file', 'r') as input_file, open('new_file', 'w') as output_file:
    for line in input_file:
        if line.strip() == 'to replace':
            output_file.write('new line\n')
        else:
            output_file.write(line)
回答by elyase
import fileinput
for line in fileinput.input('inFile.txt', inplace=True): 
      print line.rstrip().replace('oldLine', 'newLine'),
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.
这会将所有行替换为 text 'oldLine',如果您只想替换第一行,那么您需要添加一个条件并跳出循环。
Adding rstrip() avoids adding an extra space after each line
添加 rstrip() 避免在每行后添加额外的空格

