In our previous blog post, we have learned how to read files with Python, and now we will write content into a file with Python.
Writing
In the following code example, we start with opening a file called file1.txt into a file object called fileobject.
We also use a variable called content to save a text string to write to the file.
The last line of code writes the string inside content into the file01.txt
fileobject = open ("file1.txt", 'w')
content = "Hello world"
fileobject.write(content)
fileobject.close()
Note: To append content to a file without overwriting the file, use the line below (a)
fileobject = open ("file1.txt", 'a')