Python Lesson – 4.8 Writing on files

Python Lessons - 4.8 Writing on files

Writing in a file

In the previous section we saw how to read the contents of a text file. In this section we will see how to write in a file.

To write to a file, first you must open a file in writing mode, and then use the write () method specifying as an argument what we want to write.

file = open("prova.txt", "w")
file.write("Questo è il nuovo testo\n")
file.close

If you go to open the file prova.txt you will find only one line. If the file did not exist, Python takes care of creating a new one with that name. If instead we wanted to add some text to the previous text without losing the content, we have to open the file in append mode.

The write () method returns a numeric value corresponding to the number of bytes written.

file = open("prova.txt", "w")
b = file.write("Questo è il nuovo testo\n")
file.close
print(b)

By executing you get the bytes written on files that correspond to the number of characters (including the newline)

>>>
24

⇐ Go to Python Lesson 4.7 – Reading files

Go to Python Lesson 4.9  – Handling files ⇒

Leave a Reply