Last Updated : 19 Dec, 2024
Writing to a file in Python means saving data generated by your program into a file on your system. This article will cover the how to write to files in Python in detail.
Creating a FileCreating a file is the first step before writing data to it. In Python, we can create a file using the following three modes:
Example:
Python
# Write mode: Creates a new file or truncates an existing file
with open("file.txt", "w") as f:
f.write("Created using write mode.")
f = open("file.txt","r")
print(f.read())
# Append mode: Creates a new file or appends to an existing file
with open("file.txt", "a") as f:
f.write("Content appended to the file.")
f = open("file.txt","r")
print(f.read())
# Exclusive creation mode: Creates a new file, raises error if file exists
try:
with open("file.txt", "x") as f:
f.write("Created using exclusive mode.")
except FileExistsError:
print("Already exists.")
Created using write mode. Created using write mode.Content appended to the file. Already exists.Writing to an Existing File
If we want to modify or add new content to an already existing file, we can use two methodes:
write mode ("w"): This will overwrite any existing content,
writelines(): Allows us to write a list of string to the file in a single call.
Example:
Python
# Writing to an existing file (content will be overwritten)
with open("file1.txt", "w") as f:
f.write("Written to the file.")
f = open("file1.txt","r")
print(f.read())
# Writing multiple lines to an existing file using writelines()
s = ["First line of text.\n", "Second line of text.\n", "Third line of text.\n"]
with open("file1.txt", "w") as f:
f.writelines(s)
f = open("file1.txt","r")
print(f.read())
Written to the file. First line of text. Second line of text. Third line of text.
Explanation:
When dealing with non-text data (e.g., images, audio, or other binary data), Python allows you to write to a file in binary mode. Binary data is not encoded as text, and using binary write mode ("wb"
) ensures that the file content is handled as raw bytes.
Example:
Python
# Writing binary data to a file
bin = b'\x00\x01\x02\x03\x04'
with open("file.bin", "wb") as f:
f.write(bin)
f = open("file.bin","r")
print(f.read())
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4