r+ , w+ and a+ Modes in Text File

      1. Meaning of r+ , w+ and a+

  • These modes are read + write combination modes.
  • They allow both reading and writing operations on a file.

     r+ Mode (Read and Write)

  • Opens file for both reading and writing.

  • File must exist, otherwise error.

  • Writing starts from the beginning of the file (overwrites existing content).

  • The file pointer starts at position 0.

f = open("data.txt", "r+")       #Syntax
print(f.read())          # Reads existing data
f.seek(0)                # Move pointer to beginning
f.write("Updated Data")  # Overwrites from start
f.close()

 w+ Mode (Write and Read)

  • Opens file for writing and reading.

  • If file exists, it is cleared (old data deleted).

  • If file does not exist, a new file is created.

  • Writing starts from beginning.

  • You can read after writing by using seek(0) to move pointer to start.

f = open("data.txt", "w+")     #syntax
f.write("Python is powerful!\n")
f.seek(0)                # Move pointer to beginning
print(f.read())          # Read newly written content
f.close()

       a+ Mode (Append and Read)

  • Opens file for appending and reading.

  • If file does not exist, it creates a new file.

  • Writing always starts at end of file (old data not deleted).

  • Can read file, but you may need seek(0) to read from start.

f = open("data.txt", "a+")   #syntax
f.write("\nNew line added at end.")
f.seek(0)                # Move pointer to start for reading
print(f.read())          # Read entire file
f.close()

       Examples-

# r+ example
f = open("demo.txt", "r+")
print(f.read())
f.write("\nUpdated using r+")
f.close()

# w+ example
f = open("demo.txt", "w+")
f.write("Written using w+ mode\n")
f.seek(0)
print(f.read())
f.close()

# a+ example
f = open("demo.txt", "a+")
f.write("Appended using a+ mode\n")
f.seek(0)
print(f.read())
f.close()

Leave a Reply

Your email address will not be published. Required fields are marked *