【问题标题】:how to update a text in a file line by line如何逐行更新文件中的文本
【发布时间】:2017-07-23 23:37:29
【问题描述】:

我有一个文本文件 foo.txt,它看起来像:

first 01
start
some thing 01  
and more 101  
i dont care  
end  
i dont care  
final 01  

我想将 start 行之间的所有 01 替换为 10像这样在同一个 foo.txt 中结束

first 01
start
some thing 10
and more 110
i dont care
end
i dont care
final 01

到目前为止,我的代码如下所示:

import re
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replace(foo.txt):
    searchStart = re.compile("^start")
    searchEnd = re.compile("^end")
    pattern = "01"
    subst = "10"
    fh, abs_path = mkstemp()
    search = 0
    with open(abs_path,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                if searchEnd.search(line):
                    search = 0
                elif searchStart.search(line):
                    search = 1
                if search == 1:
                    new_file.write(re.sub(pattern,subst,line))
                else:
                    new_file.write(line)
    close(fh)
    remove(foo.txt)
    move(abs_path, foo.txt)

它可以满足我的需求,但我想知道是否有其他有效的方法来编写代码。我来自嵌入式背景,所以我在我的代码中使用了 flag,例如 search

谢谢!

【问题讨论】:

    标签: python-3.x file search replace


    【解决方案1】:

    我不太确定您想要逐行读取和写入文件的用例,但不是您的方法,我只是将文件读入字符串变量,然后替换所有出现的 '01'与“10”。您的代码看起来像这样。

    with open('testPy.txt', "r+") as f:
        data = f.read().replace('01', '10')
        f.seek(0)
        f.write(data)
    

    seek(0) 函数将您的文件偏移量设置为文件的开头。因此,从这一点开始写入将覆盖整个文件。

    【讨论】:

    • 感谢您的建议。但我不想替换整个文件我只想替换开始和结束之间的行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2022-11-05
    相关资源
    最近更新 更多