Last answered:

07 Sept 2023

Posted on:

28 Sept 2022

1

Resolved: Difference between multiple writes and append

Earlier we made the 'kipling.txt' file by writing onto it several lines. What's the difference between writing several write statements and writing append statements?

4 answers ( 1 marked as helpful)
Instructor
Posted on:

29 Sept 2022

4

Hey,

Thank you for reaching out!

Let me demonstrate the difference between the two modes with an example. Consider the following code:

file = open('sample.txt','w')
file.write("Line 1\n")
file.write("Line 2\n")
file.close()

file = open('sample.txt','w')
file.write("Line 3\n")
file.write("Line 4")
file.close()

We create a sample.txt file and write "Line 1" and "Line 2" inside; the file is then closed. Afterwards, we open the file again and add two more lines. Upon opening the file, we would be quite disappointed, as the first version of the file would be deleted, a new file with the same name would be created, and the text "Line 3" and "Line 4" will be added.

Let's now change the code as follows:
1. Open the file in 'w' mode
2. Write "Line 1" and "Line 2"
3. Close the file
4. Open the file again in 'a' mode
5. Append "Line 3" and "Line 4"
6. Close the file.

This time, by opening the file the second time, we are appending to the old text rather than overriding it.

The conclusion is the following: when opening a file in write mode, you are creating a file (if it doesn't exist) or deleting an existing file with the same name and thus creating a new one. When opening a file in append mode, you are creating a file (if it doesn't exist) or opening an existing one and thus being able to append information to the old one.

Hope this helps!

Kind regards,
365 Hristina

Posted on:

29 Sept 2022

0

Hi Hristina,

Yes, that absolutely helps explaining the difference. Thank you so much for the good example.

Posted on:

31 Jan 2023

0

Thanks to both of you for the helpful conversation!

Posted on:

07 Sept 2023

0

Very helpful conversation indeed.

Submit an answer