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.
Complete Python Bootcamp: Go from zero to hero in Python 3
Create file for writing
The code below creates a new file (or overwrites) with the data.
#!/usr/bin/env python # Filename to write filename = "newfile.txt" # Open the file with writing permission myfile = open(filename, 'w') # Write a line to the file myfile.write('Written with Python\n') # Close the file myfile.close()
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.
#!/usr/bin/env python # Filename to append filename = "newfile.txt" # The 'a' flag tells Python to keep the file contents # and append (add line) at the end of the file. myfile = open(filename, 'a') # Add the line myfile.write('Written with Python\n') # Close the file myfile.close()
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)|