How to write in a file without erasing old things?

1

Example: in my file you have

joao
maria
carla

If I use:

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

It will delete the previous ones that was joao, maria, how do I write without deleting the previous txt?

    
asked by anonymous 28.04.2017 / 17:40

1 answer

4

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

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

There are also modes r+ , w+ and a+ . They all open the file for read and write .

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

w+ : Opens the file for reading and writing. The stream is placed 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 also be nice to make use of with .

You can see more about it this question 1 .

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

1 What is with in Python?

    
28.04.2017 / 17:53