Writing to file in Python
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 File
Creating a file is the first step before writing data to it. In Python, we can create a file using the following three modes:
- Write ("w") Mode: This mode creates a new file if it doesn't exist. If the file already exists, it truncates the file (i.e., deletes the existing content) and starts fresh.
- Append ("a") Mode: This mode creates a new file if it doesn't exist. If the file exists, it appends new content at the end without modifying the existing data.
- Exclusive Creation ("x") Mode: This mode creates a new file only if it doesn't already exist. If the file already exists, it raises a FileExistsError.
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.")
OutputCreated 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())
OutputWritten to the file. First line of text. Second line of text. Third line of text.
Explanation:
- open("example.txt", "w"): Opens the file example.txt in write mode. If the file exists, its content will be erased and replaced with the new data.
- file.write("Written to the file."): Writes the new content into the file.
- file.writelines(lines): This method takes a list of strings and writes them to the file. Unlike write() which writes a single string writelines() writes each element in the list one after the other. It does not automatically add newline characters between lines, so the \n needs to be included in the strings to ensure proper line breaks.
Writing to a Binary File
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:
- bin= b'\x00\x01\x02\x03\x04': The b before the string indicates that this is binary data. Each pair represents a byte value.
- open("file.bin", "wb"): Opens the file file.bin in binary write mode. If the file doesn't exist, Python will create it.
- file.write(bin): Writes the binary data to the file as raw bytes.
Similar Reads
Writing CSV files in Python CSV (Comma Separated Values) is a simple file format used to store tabular data, such as spreadsheets or databases. Each line of the file represents a data record, with fields separated by commas. This format is popular due to its simplicity and wide support.Ways to Write CSV Files in PythonBelow ar
11 min read
Python - Write Bytes to File Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps:Open filePerform operationClose fileThere are four basic modes in which a file can
3 min read
Reading and Writing to text files in Python Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
8 min read
Read File As String in Python Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
3 min read
Setting file offsets in Python Prerequisite: seek(), tell() Python makes it extremely easy to create/edit text files with a minimal amount of code required. To access a text file we have to create a filehandle that will make an offset at the beginning of the text file. Simply said, offset is the position of the read/write pointer
4 min read