Python Write/Create Files
Python: Writing and Creating Files
Python makes it easy to write or create files using its built-in open() function. You can write text, numbers, or even binary data to files. Let’s look at how to write and create files in Python.
Opening a File for Writing
To write to a file, you must open it in one of the following modes:
'w'(write mode): Opens the file for writing. If the file already exists, it overwrites the content. If the file doesn’t exist, it creates a new file.'a'(append mode): Opens the file for writing and appends data to the end of the file without overwriting existing content.'x'(exclusive creation mode): Creates a new file. Raises an error if the file already exists.'t'(text mode): Opens the file in text mode (default).'b'(binary mode): Opens the file in binary mode (used for binary files like images, videos, etc.).
1. Writing to a File: write() Method
The write() method allows you to write content to a file. This method overwrites the file if it already exists.
Example 1: Writing to a File
# Open the file in write mode
file = open("file.txt", "w")
# Write some text to the file
file.write("Hello, world!\n")
file.write("This is another line of text.")
# Close the file
file.close()
This will create (or overwrite) file.txt with the given content:
Hello, world!
This is another line of text.
2. Appending to a File: write() Method
If you want to add content to the end of an existing file without overwriting it, open the file in append mode ('a').
Example 2: Appending to a File
# Open the file in append mode
file = open("file.txt", "a")
# Append some more text
file.write("\nThis text is appended to the file.")
# Close the file
file.close()
The new content will be added to the end of the file:
Hello, world!
This is another line of text.
This text is appended to the file.
3. Using the with Statement to Write Files
The with statement is recommended because it automatically closes the file after writing, even if exceptions occur. This helps to manage file resources more efficiently.
Example 3: Writing to a File Using with
with open("file.txt", "w") as file:
file.write("This is written using the with statement.\n")
file.write("The file is automatically closed after this block.")
This writes the text to file.txt and automatically closes the file when the block ends.
4. Writing Multiple Lines: writelines() Method
The writelines() method allows you to write multiple lines to a file. You must provide a list of strings, and each string will be written to the file in order.
Example 4: Writing Multiple Lines
lines = [
"First line\n",
"Second line\n",
"Third line\n"
]
# Open the file in write mode
with open("file.txt", "w") as file:
file.writelines(lines)
The file will contain:
First line
Second line
Third line
Note: The writelines() method does not add newline characters (\n) automatically, so make sure to include them if necessary.
5. Writing Binary Files
If you’re working with binary data (such as images, videos, or files with non-text content), you should open the file in binary mode ('wb' for writing and 'ab' for appending).
Example 5: Writing to a Binary File
# Binary data to write (for example, a byte array)
binary_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10'
# Open file in binary write mode
with open("binary_file.bin", "wb") as file:
file.write(binary_data)
This writes the raw binary data to binary_file.bin. For binary data, you would typically be handling files such as images, sound files, or other binary formats.
6. Creating a New File: x Mode
To ensure you’re creating a new file and not accidentally overwriting an existing one, you can use the 'x' mode. This mode raises an error if the file already exists.
Example 6: Creating a New File
# Try to create a new file (raises an error if file already exists)
try:
with open("new_file.txt", "x") as file:
file.write("This file was created using 'x' mode.")
except FileExistsError:
print("File already exists.")
If new_file.txt doesn’t exist, it will be created and the text will be written. If the file already exists, a FileExistsError will be raised.
7. Writing Numbers to a File
When writing numbers to a file, you need to convert them to strings, as the write() method only accepts strings.
Example 7: Writing Numbers to a File
with open("numbers.txt", "w") as file:
for i in range(1, 6):
file.write(f"Number: {i}\n")
The file numbers.txt will contain:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Writing and Creating Files Summary:
write(): Writes a string to the file. Overwrites the content if the file exists.append(): Appends new content to the end of the file.xmode: Creates a new file. Raises an error if the file already exists.writelines(): Writes a list of strings to the file.- Binary mode (
'b'): Used for writing binary data (images, etc.). withstatement: Automatically handles closing the file after writing.