Writing to a File
tags: #python/documentation/file_handling
How to write to a file? Specify Mode First
To write to an existing file, you must use the write or append parameter to the open() function.
Writing to a File
To overwrite any existing content in the entirety of the file (i.e., will erase existing content in its entirety):
file = open('filename.ext', 'w')
Appending to a File
To append to the end of the file.
file = open('filename.ext', 'a')
Methods to Write to a File
There are two ways to write in a file.
1. write()
The write() method is used to write a single string to a file. If you want to include newline characters ('\n'), you need to include them explicitly in the string.
Example: write() in w mode
with open('example.txt', 'w') as file:
file.write('Line 1\n') # Writing a single line
file.write('Line 2\n') # Writing another line
1. writelines()
The writelines() method is used to write a list of strings to a file. It does not add newline characters between the strings by default (i.e., it writes the lines as they are provided in the iterable (e.g., a list of strings). If you want newlines between lines, you need to include them explicitly in the strings).
Example:
lines = ['Line 1', 'Line 2', 'Line 3'] # no newline characters between the lines.
# Using writelines without explicit newlines
with open('example.txt', 'w') as file:
file.writelines(lines)
To specify each line to be written on a new line in the file:
lines_with_newlines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
# Using writelines with explicit newlines
with open('example.txt', 'w') as file:
file.writelines(lines_with_newlines)
Line 1
Line 2
Line 3