gpt4 book ai didi

python - 尝试 'a+' 同时读取和附加但没有用

转载 作者:太空宇宙 更新时间:2023-11-03 15:58:55 25 4
gpt4 key购买 nike

这些是 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", "")

它什么也没做。

最佳答案

正确的做法是先完整读取内容,修改后再写回文件。

这种方法也很干净且可读。

#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)

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

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

关于python - 尝试 'a+' 同时读取和附加但没有用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41614885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com