12/19/2023 0 Comments Python read and write file![]() You can use a to add new stuff to the end but that is about it. Textfiles in general can't be updated in place. Specifying both is asking open to point to two different locations in the file at the same time. The a or the r specifies a seek to a particular location in the file. Either you want to read it or you want to write to it. Here's a nice little diagram from another SO post: ![]() You can also use w+, but this will truncate (delete) all the existing content. (Further Reading: What's the difference between 'r+' and 'a+' when open file in python?) with open("filename", "r+") as f:į.seek(0) # return to the top of the file If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0). # after reading, the position is pushed toward the end # here, position is initially at the beginning With a+, the position is initially at the end. With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. You're looking for the r+/ a+/ w+ mode, which allows both read and write operations to files.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |