Writing to a file in Python is a fundamental operation that allows you to store data persistently. This can be done in several ways, depending on the mode in which you open the file and the type of data you’re writing. Here’s a detailed overview of writing to a file, including different methods, modes, and error handling.
You can open a file for writing using the open()
function. There are several modes you can use:
'w'
: Write mode. Opens the file for writing and truncates the file to zero length (i.e., it deletes the content of the file if it already exists).'a'
: Append mode. Opens the file for writing, appending to the end of the file if it exists.'x'
: Exclusive creation. Opens the file for writing only if it does not exist. Raises a FileExistsError
if the file exists.'b'
: Binary mode. Used with other modes (e.g., 'wb'
, 'ab'
) to write binary data.'+'
: Update mode. Used with other modes (e.g., 'w+'
, 'a+'
) to open a file for updating (reading and writing).write()
The write()
method writes a string to the file.
# Write mode
with open('example.txt', 'w') as file:
file.write('Hello, world!\n')
file.write('This is a new line.\n')
# Append mode
with open('example.txt', 'a') as file:
file.write('Appending a new line.\n')
writelines()
The writelines()
method writes a list of strings to the file. Each string in the list will be written exactly as it is.
lines = ['First line\n', 'Second line\n', 'Third line\n']
with open('example.txt', 'w') as file:
file.writelines(lines)
To write binary data, open the file in binary mode ('wb'
, 'ab'
).
# Writing binary data
data = b'\x00\x01\x02\x03\x04'
with open('binary_file.bin', 'wb') as file:
file.write(data)
with
StatementUsing the with
statement is recommended because it ensures that the file is properly closed after its suite finishes, even if an exception is raised.
with open('example.txt', 'w') as file:
file.write('Hello, world!')
Combining all these aspects into a comprehensive example:
def write_text_file(file_name, lines, mode='w'):
try:
with open(file_name, mode) as file:
file.writelines(lines)
print(f"Data written to {file_name} successfully.")
except FileNotFoundError:
print(f"The file {file_name} was not found.")
except PermissionError:
print(f"You do not have permission to write to the file {file_name}.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example usage
lines_to_write = ['Hello, world!\n', 'This is a new line.\n']
write_text_file('example.txt', lines_to_write, 'w')
# Appending to the same file
append_lines = ['Appending this line.\n']
write_text_file('example.txt', append_lines, 'a')