How do you replace a line of text in a text file (python) [duplicate]

岁酱吖の 提交于 2019-12-18 07:17:39

问题


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 1 to unknown value 0.

How can I accomplish this?


回答1:


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.

Adding rstrip() avoids adding an extra space after each line




回答2:


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)


来源:https://stackoverflow.com/questions/16622754/how-do-you-replace-a-line-of-text-in-a-text-file-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!