September 2026
1051 pages
35h 4m
English
In the previous section, we focused on reading files. The fact that it also works the other way around is the topic of this section. To open a file for writing, we also use the built-in open function. You’ll remember that this function expects a mode as second parameter, which had to be "r" for read in the last section. Similarly, "w" (for write) must be specified if the file is to be opened for writing. If the desired file already exists, it will be emptied. A file that doesn’t exist yet will be created:
fobj = open("output.txt", "w")
After all data has been written to the file, the file object must be closed by calling the close method:
fobj.close()
Also, when writing a file, you should use the with statement ...
Read now
Unlock full access