How to write in a file without erasing old things?

Asked

Viewed 7,728 times

2

Example: in my file has

joao
maria
carla

if I use:

arq = open('nomes.txt')
arq.write('jose')
arq.write('\n')
arq.close

it will erase the previous ones that was Joao, maria,how do I write without deleting the previous ones from txt?

1 answer

6


Pass as second parameter to string 'a', This says that you are opening the file to update it.

The second function parameter open is a string which indicates how the file should be opened, the most common is to use w which serves for writing, truncating the file, if it already exists, r for reading the file and a which serves to add content to the file.

There are also modes r+, w+ and a+. They all open the file to reading and writing.

r+: opens the file for reading and writing. The stream is positioned at the beginning of the file.

w+: opens the file for reading and writing. The stream is positioned at the beginning of the file and the file will be created if it does not exist.

a+: opens the file for reading and writing. The file will be created if it does not exist and the stream is positioned at the end of the file.

It would be nice to also make use of the with.

You can see more about him in this question1.

with open('nomes.txt', 'a') as arq:
    arq.write('jose')
    arq.write('\n')

1What’s with no Python for?

  • Thanks! , that’s what I’ve been wanting.

  • Do you mind documenting the "w+" and "r+" modes of opening a file as well? - I always find it hard to find information about opening an update file from the beginning ("r+" ) and being in one more place wouldn’t hurt.

  • @jsbueno I thank you feedback. I made the edit by adding these three modes so that it didn’t lengthen the answer too much. Any suggestion is welcome.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.