Python supports writing files by default, no special modules are required. You can write a file using the .write() method with a parameter containing text data.
Before writing data to a file, call the open(filename,’w’) function where filename contains either the filename or the path to the filename. Finally, don’t forget to close the file.
Python Programming Bootcamp: Go from zero to hero
Create file for writing
The code below creates a new file (or overwrites) with the data.
The ‘w’ flag makes Python truncate the file if it already exists. That is to say, if the file contents exists it will be replaced.
Append to file
If you simply want to add content to the file you can use the ‘a’ parameter.
A summary of parameters:
|r||Open file for reading|
|w||Open file for writing (will truncate file)|
|r+||open file for reading and writing|
|a+||open file for reading and writing (appends to end)|
|w+||open file for reading and writing (truncates files)|