简体   繁体   English

如何仅替换文件中的一个指定行(在python中)

[英]How to replace just one specified line inside a file (in python)

I have a file and wanna replace a specific line that I can find it with search in file.我有一个文件,想用在文件中搜索来替换我可以找到它的特定行。 I do that likes the following from this post :我这样做喜欢这篇文章中的以下内容:

import fileinput
new_line = 'some text'
with fileinput.FileInput(file_addr, inplace=True) as file:
    for line in file:
        if 'keyword' in line:
             line = new_line
             # Here #
        print(line)

Now I want to terminate the loop in # Here # .现在我想终止# Here #中的循环。 In this point, I found the line and replace it.在这一点上,我找到了这条线并替换它。 But if I break the loop, the rest of the file will not be written into the file and will be removed.但是如果我break循环,文件的rest不会被写入文件,会被删除。 I am looking for a method just replace line when finding it and then terminate the loop.我正在寻找一种方法,只需在找到它时替换行,然后终止循环。 The reason is the length of the file could be high and I don't wanna loop over the rest of the file.原因是文件的长度可能很高,我不想遍历文件的 rest。

Also, if there is a solution for the both case that the length of new_line is the same as the length of the line or not (if it is matter).此外,如果有两种情况的解决方案,即new_line的长度是否与行的长度相同(如果重要的话)。

You can only do this if the replacement line is the same length as the original line.仅当替换线与原始线的长度相同时,您才能执行此操作。 Then you can do it by opening the file in read-write mode and overwriting the line in the file.然后,您可以通过以读写模式打开文件并覆盖文件中的行来做到这一点。

new_line = 'some text'
with open(file_addr, 'r+') as f:
    while True:
        line = f.readline()
        if 'keyword' in line:
            f.seek(-len(line), 1)
            f.write(new_line)
            break

You can turn the part of your code to generator:您可以将部分代码转换为生成器:

lines = (line if 'keyword' not in line else new_line for line in file)

then you just write it to a file然后你只需将它写入文件

with file(new_file, 'r') as new_file:
    new_file.writelines(lines)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM