尝试'a +'同时阅读和追加,但没有奏效

时间:2017-01-12 13:50:29

标签: python

这些是contacts.txt文件的内容:

  

foo 69

     

bar 70

     

baz 71

我想删除“foo 69”,这就是我所做的:

with open('contacts.txt','a+') as f:
    for line in f:
        with open('contacts.txt','a+') as f:
            if "foo" in line:
                line.replace("foo", "")

它没有做任何事情。

2 个答案:

答案 0 :(得分:2)

正确的方法是先完全阅读内容,进行修改,然后再写回文件。

这种方法也很简洁,也是可读的。

with open('file_name','a+') as f:
    for line in f:#here you are iterating through the content of the file
        # at each iteration line will equal foo 69, then bar 70 and then bar 71...

        # Now, there is no reason to open the file here again, I guess you opened
        # it to write again, but your mode is set to `a` which will append contents
        # not overwrite them
        with open('contacts.txt','a+') as f:
            if "foo" in line:
                line.replace("foo", "") #here the modified content is lost
                # because you're not storing them anywhere

现在,我已经评论了您在代码中遇到的一些问题:

to_replace = 'foo 69\n' #note \n is neccessary here
with open('input.txt','r') as input_file:
    with open('ouput.txt','w') as output:
        for line in input_file:
            if line!=to_replace:
                output.write(line)


#Now, let's say you want to delete all the contents of the input_file
#just open it in write mode and close without doing anything
input_file = open('input_file.txt','w')
input_file.close()

# If you want to delete the entire input_file and rename output_file to
# original file_name then you can do this in case of linux OS using subprocess
subprocess.call(['mv', 'output_file.txt', 'input_file.txt'])

修改 - 如评论中所述,如果您的文件非常大而且您不想阅读所有内容。

然后,最好的方法是逐行读取内容并将内容写入另一个文件,不包括您要删除的行。

input_file

这非常节省内存,因为在任何时间点内存只有一行内容。 for line in input_file只是指向文件和迭代的指针 - std::cin不读取整个文件并开始逐个迭代内容。

答案 1 :(得分:1)

我不确定您想要输出的确切内容(例如,如果您希望删除bar 70以上的行),但此代码实际上只是删除了foo 69文件。它只需要打开一次文件引用:

with open('contacts.txt', 'r+') as f:
    content = f.read()
    new_content = content.replace('foo 69', '')
    f.seek(0)
    f.write(new_content)
    f.truncate()

在下面的代码段中,我使用.代替换行符进行格式化。

contacts.txt之前:

foo 69
.
bar 70
.
baz 71

contacts.txt之后:

.
.
bar 70
.
baz 71