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

北慕城南 提交于 2019-12-10 18:37:42

问题


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?

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:

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.

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?


回答1:


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



回答2:


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. And then write to the file.

OR (Alternate using 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.




回答3:


seek() is based on bytes, and your text file may not be encoded with precisely one byte per character. Since read() reads the whole file and leaves the pointer at the end, there's no need to seek anyway. 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")



回答4:


Why not do this? Note, the first with statement is used for creating the file, not for reading or appending. 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")


来源:https://stackoverflow.com/questions/36965852/how-do-i-read-and-append-to-a-text-file-in-one-pass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!