Home > Back-end >  How to read a file in append mode in python?
How to read a file in append mode in python?

Time:12-07

I have just recently started learning about File Handling in python. But I got stuck into a problem. As mentioned in my textbook

In append mode, both reading and writing operations can take place.

But when I tried this code:

with open('first.txt','a ') as f:
    print(f.read())

I'm getting no output. What should I do to print the contents in append mode??

CodePudding user response:

In the code you have provided, the file is opened in append mode ('a ') which means that any data written to the file will be appended to the end of the file, rather than overwriting the existing data.

However, when you use the f.read() method, the file pointer is at the end of the file, so there is no data to be read. To read the data in the file, you need to move the file pointer to the beginning of the file using the f.seek(0) method before calling f.read().

with open('first.txt','a ') as f:
  f.seek(0)
  print(f.read())

To append data to a file after reading it, you can use the f.write().

CodePudding user response:

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

CodePudding user response:

a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Open the file "first.txt" and append content to the file:

f = open("first.txt", "a") f.write("Now the file has more content!") f.close()

#open and read the file after the appending: f = open("first.txt", "r") print(f.read())

  • Related