PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

[FIXED] How to open a file in both read and append mode at the same time in one variable in python?

 November 02, 2022     file, python     No comments   

Issue

'r' will read a file, 'w' will write text in the file from the start, and 'a' will append. How can I open the file to read and append at the same time?

I tried these, but got errors:

open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")

error:

invalid mode: 'r,a'

Solution

You're looking for the r+/a+/w+ mode, which allows both read and write operations to files.

With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+, the position is initially at the end.

with open("filename", "r+") as f:
    # here, position is initially at the beginning
    text = f.read()
    # after reading, the position is pushed toward the end

    f.write("stuff to append")
with open("filename", "a+") as f:
    # here, position is already at the end
    f.write("stuff to append")

If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0).

with open("filename", "r+") as f:
    text = f.read()
    f.write("stuff to append")

    f.seek(0)  # return to the top of the file
    text = f.read()

    assert text.endswith("stuff to append")

(Further Reading: What's the difference between 'r+' and 'a+' when open file in python?)

You can also use w+, but this will truncate (delete) all the existing content.

Here's a nice little diagram from another SO post:

Decision Tree: What mode should I use?

(source)



Answered By - TrebledJ
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing