In Python we can write to file and in this lesson we will study how to do it.
After opening the file for writing we can in fact write to it!
This is an example:
f = open(“coding.txt”, ‘w’)
f.write(“Coding is essential to increase logical thinking”)
f.close () #close stream
In this simple example we created an object f on which we then used 2 methods: Python write() to file and close() a file.
The object is created using the open() function, explained in the previous lesson.
The write() method in Python allows, after opening the file, to be able to write to it. Attention, if there was already content, it will be overwritten. After, to save what is written on the file, it is necessary to close it using the close() method.
The closing operation, as we have already explained, allows the file to be saved in the mass memory.
In the write method we therefore specify the string that we want to insert in the text file.
Python write to file with append
Now suppose we want to add some text to an existing file. To do this we must use the mode = ‘a’.
Let’s take a simple example:
f = open(“coding.txt”, ‘to’)
f.write(“Have fun programming in Python.”)
f.close() #close stream
If we open the coding.txt file we can see that the text is attached to the previous code. How can we go about writing the sentence to a new line?
We could simply write:
f.write(“\ nFun programming in Python”)
We added \n to wrap and start typing on a new line.
In this lesson we learned how in Python we can write to files, in the next lesson we will continue to do examples.