如何一遍阅读并附加到文本文件? [英] How do I read and append to a text file in one pass?

查看:112
本文介绍了如何一遍阅读并附加到文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查字符串是否在文本文件中,然后如果不存在则追加该字符串.

I want to check if a string is inside a text file and then append that string if it's not there.

我知道我可以通过创建两个单独的with方法来做到这一点,一个方法用于读取,另一个方法用于附加,但是可以在同一个with方法内部进行读取和附加吗?

I know I can probably do that by creating two separate with methods, one for reading and another for appending, but is it possible to read and append inside the same with method?

我想出的最接近的是:

with open("file.txt","r+") as file:
    content=file.read()
    print("aaa" in content)
    file.seek(len(content))
    file.write("\nccccc")

我的file.txt:

My file.txt:

aaaaa
bbbbb

当我第一次运行代码时,我得到了:

When I run the code for the first time, I get this:

aaaaa
bbbbb
ccccc

但是如果我再次运行它,它就会出现:

but if I run it again, this comes up:

aaaaa
bbbbb
ccc
ccccc

我希望第三行是ccccc.

任何人都可以解释为什么在第二次运行中最后两个字符被截断了吗?另外,如何阅读文本并将其附加到文件?

Anyone can explain why the last two characters are truncated in the second run? Also, how do I read and append text to a file?

推荐答案

请勿在文本文件上使用seek.在所有情况下,内容的长度都不是文件的长度.使用二进制文件读取或使用两个单独的withs:

Don't use seek on text-files. The length of the contents is not the length of the file in all cases. Either use binary file reading or use two separate withs:

with open("file.txt","r") as file:
    content=file.read()
print("aaa" in content)
with open("file.txt","a") as file:
    file.write("\nccccc")

这篇关于如何一遍阅读并附加到文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆