简体   繁体   English

如何一次读取和附加到文本文件?

[英]How do I read and append to a text file in one pass?

I want to check if a string is inside a text file and then append that string if it's not there. 我想检查一个字符串是否在文本文件中,然后附加该字符串,如果它不存在。

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方法,一个用于读取,而另一个用于追加,但有可能读取和附加内同样with方法?

The closest I came up with is this: 我想出的最接近的是:

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

My file.txt: 我的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

I would expect the third line to be 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? 另外,如何读取文本并将其附加到文件中?

Don't use seek on text-files. 不要在文本文件上使用seek 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: 要么使用二进制文件读取,要么使用两个单独的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")

Use this: 用这个:

with open("file.txt","r+") as file:
    content=file.read()
    file.seek(0,2)
    file.write("\nccccc")

Here we use fileObject.seek(offset[, whence]) with offset 0 & whence 2 that is seek to 0 characters from the end. 这里我们使用fileObject.seek(offset[, whence])offset 0whence 2 ,它从末尾寻找0个字符。 And then write to the file. 然后写入文件。

OR (Alternate using SEEK_END): 或(使用SEEK_END替代):

import os
with open("file.txt", 'rb+') as file:
    file.seek(-1, os.SEEK_END)
    file.write("\nccccc\n")

Here we seek to SEEK_END of the file(with the os package) and then write to it. 在这里,我们寻求文件的SEEK_END (使用os包),然后写入它。

seek() is based on bytes, and your text file may not be encoded with precisely one byte per character. seek()基于字节,并且您的文本文件可能不会使用每个字符恰好一个字节进行编码。 Since read() reads the whole file and leaves the pointer at the end, there's no need to seek anyway. 由于read()读取整个文件并将指针留在最后,因此无需进行搜索。 Just remove that line from your code and it will work fine. 只需从代码中删除该行,它就可以正常工作。

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

Why not do this? 为什么不这样做? Note, the first with statement is used for creating the file, not for reading or appending. 注意,第一个with语句用于创建文件,而不是用于读取或追加。 So this solutions uses only one with to read and append. 所以这个解决方案只使用一个来读取和追加。

string="aaaaa\nbbbbb"
with open("myfile", "w") as f:
    f.write(string)

with open("myfile", "r+") as f:
    if not "ccccc" in f.read():
        f.write("\nccccc")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM