附加文本文件而不是覆盖它

时间:2015-06-27 10:24:20

标签: python file

上下文是以下内容,我有两个需要编辑的文本文件。 我打开第一个文本文件,逐行读取并编辑它,但有时当我遇到第一个文本文件中的特定行时,我需要覆盖第二个文件的内容。

但是,每次重新打开第二个文本文件而不是覆盖其内容时,下面的代码会将其附加到文件中...

提前致谢。

def edit_custom_class(custom_class_path, my_message):
    with open(custom_class_path, "r+") as file: 
        file.seek(0)
        for line in file:
            if(some_condition):
                file.write(mu_message)

def process_file(file_path):
     with open(file_path, "r+") as file:    
        for line in file:
            if(some_condition):
                edit_custom_class(custom_class_path, my_message)

1 个答案:

答案 0 :(得分:0)

在我看来,同时阅读和修改文件是件坏事。考虑使用这样的东西。首先读取文件,进行修改,然后完全覆盖该文件。

def modify(path):
    out = []
    f = open(path)
    for line in f:
        if some_condition:
            out.append(edited_line) #make sure it has a \n at the end
        else:
            out.append(original_line)
    f.close()
    with open(path,'w') as f:
        for line in out:
            f.write(line)