Writing to file in Python Last Updated : 19 Dec, 2024 Comments Improve Suggest changes Like Article Like Report 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: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 FileIf 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 FileWhen 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()) Output 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. Comment More infoAdvertise with us Next Article Writing to file in Python N nikhilaggarwal3 Follow Improve Article Tags : Python python-file-handling Practice Tags : python 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 Reading and Writing JSON to a File in Python The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho 3 min read Reading and Writing CSV Files in Python CSV (Comma Separated Values) format is one of the most widely used formats for storing and exchanging structured data between different applications, including databases and spreadsheets. CSV files store tabular data, where each data field is separated by a delimiter, typically a comma. Python provi 4 min read Reading and Writing lists to a file in Python Reading and writing files is an important functionality in every programming language. Almost every application involves writing and reading operations to and from a file. To enable the reading and writing of files programming languages provide File I/O libraries with inbuilt methods that allow the 5 min read Writing files in background in Python How to write files in the background in Python? The idea is to use multi-threading in Python. It allows us to write files in the background while working on another operation. In this article, we will make a 'Asyncwrite.py' named file to demonstrate it. This program adds two numbers while it will al 2 min read Write a dictionary to a file in Python A dictionary store data using key-value pairs. Our task is that we need to save a dictionary to a file so that we can use it later, even after the program is closed. However, a dictionary cannot be directly written to a file. It must first be changed into a format that a file can store and read late 3 min read Like