Python 编辑大文件中的特定行

Python 编辑大文件中的特定行,python,Python,我想在特定行中编辑一个大文件。 所以在编辑之前阅读整个文件不是一个好主意,这就是为什么我不这么做 要使用: myfile.readlines() 我必须阅读每一行,检查其中是否有特殊内容,然后我必须编辑这一行 到目前为止,我阅读了每一行: file = open("file.txt","r+") i = 0 for line in file: if line ......: //edit this line //this is where i need

我想在特定行中编辑一个大文件。 所以在编辑之前阅读整个文件不是一个好主意,这就是为什么我不这么做 要使用:

myfile.readlines()
我必须阅读每一行,检查其中是否有特殊内容,然后我必须编辑这一行

到目前为止,我阅读了每一行:

file = open("file.txt","r+")
i = 0
for line in file:
    if line ......:
        //edit this line
        //this is where i need help


file.close()
因此,问题是: 如何编辑If语句中的当前行,例如: 如果当前行是test,我想用test2替换它,然后将test2写回到文件中test之前所在的行中,这将有所帮助

import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

好的,正如@EzzatA在下面的问题评论中提到的,这似乎是读取原始文件并使用编辑的数据创建新文件的最佳方式。 比如说:

original_file = open("example.txt","r")
new_file = open("example_converted.xml","w")

string_tobe_replace = "test"
replacement_string = "test2"

for line in original_file:
    if string_tobe_replace in line:
        new_line = line.replace(string_tobe_replace,replacement_string)
        new_file.write(new_line)
    else:
        new_file.write(line)



original_file.close()
new_file.close()

那么..你的问题是什么?我如何编辑if语句中的特定行line将成为str对象,因此只需像对待任何str对象一样对待它..我建议你阅读此文,我认为你没有理解我的问题。。。。我知道我不应该使用readlines,这就是我不使用它的原因。我的问题是将编辑的行写回到编辑前的行中。