尝试“a+”同时读取和附加,但没有

2024-04-24 04:21:49 发布

您现在位置: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", "")

它什么也没做。在


Tags: 文件intxt内容foriffooas
1条回答
网友
1楼 · 发布于 2024-04-24 04:21:49

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

这种方法也很简洁易读。在

#first read everything
with open('file_name','r') as f:
        content =  f.read()

#now perform modifications
content = content.replace('foo 69','')

#now write back to the file
with open('file_name','w') as f:
        f.write(content)

现在,我对代码中的一些问题进行了评论:

^{pr2}$

编辑-如注释中所述,如果文件很大,并且您不想阅读所有内容。在

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

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不会读取整个文件并开始逐个迭代内容。在

网友
2楼 · 发布于 2024-04-24 04:21:49

我不确定您到底希望输出是什么样的(例如,如果您希望删除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之前:

^{pr2}$

contacts.txt之后:

.
.
bar 70
.
baz 71

相关问题 更多 >