For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
Whether you're logging data, saving user input, or exporting results, writing to a file is a core skill in Python programming. The Python write file operation lets you store information outside your program so it can be reused, shared, or analyzed later. In this guide, we’ll dive deep into how to write to file in Python using built-in functions and best practices.
Also, if you’ve ever wondered:
You're in the right place.
We'll walk through every essential detail, using simple language, clear examples, and plenty of code snippets. Each example will come with explanations and expected output to help you master the art of file writing in Python. Also, all this will help you in your journey to become an expert Python developer.
So, whether you're a beginner or brushing up your skills, this blog will cover everything you need to know about how to write to file in Python, from creating a file to writing plain text, appending data, and even working with binary files. Additionally, it’ll build the foundation for expert-level software development courses.
When it comes to the Python write file process, one of the most commonly used methods is `write()`. This method is part of Python’s built-in file handling system, and it allows you to write string data directly to a file.
The `write()` method is used when you want to write to file in Python—whether you're creating a new file or updating an existing one. The most important thing to remember is that `write()` only works with string data. If you want to write something else, like a list or integer, you’ll need to convert it first.
Also learn Global Variable in Python to develop advanced level programs.
Here’s a simple example to help you understand how `write()` works.
Example: Using `write()` to Write to a File in Python
# Open a file named "example.txt" in write mode
with open("example.txt", "w") as file:
# Writing a simple string to the file
file.write("Hello, world! This is a Python write file example.")
Output:
This code does not display output in the terminal, but it creates a file named `example.txt` with the following content:
Hello, world! This is a Python write file example.
Explanation:
This is the foundation of how to write to file in Python. Next, we’ll explore more ways to write data using `writelines()` and even structured data with `writerows()`.
Pilot your high-paying career with the following full-stack development courses:
Once you're comfortable with the `write()` method, it's time to expand your file-handling toolkit. Python offers several methods for writing data to files, each tailored to specific use cases. In this section, we’ll explore three commonly used approaches to write to file in Python: `write()`, `writelines()`, and `writerows()` from the `csv` module.
Each of these methods plays a distinct role in the broader Python write file workflow.
You’ve already seen how `write()` can be used to store a single string in a file. Here's another quick example to reinforce the idea:
# Open the file in write mode
with open("single_line.txt", "w") as file:
# Write a single line of text
file.write("This is a single line written to the file.")
Output:
Contents of `single_line.txt`:
This is a single line written to the file.
Explanation:
Use `write()` when you need to write a single string or line at a time. This is the most direct way to write to file in Python.
Also, learn about List Methods in Python for in-depth understanding of the Python programming.
When you have a list of strings and want to write them to a file in one go, `writelines()` is your friend. It writes a sequence of strings without adding newlines automatically, so you’ll need to include `\n` manually if needed.
# Prepare a list of lines to write
lines = [
"First line of text\n",
"Second line of text\n",
"Third line of text\n"
]
# Write multiple lines using writelines()
with open("multiple_lines.txt", "w") as file:
file.writelines(lines)
Output:
Contents of `multiple_lines.txt`:
First line of text
Second line of text
Third line of text
Explanation:
`writelines()` is ideal for bulk writing when you're working with a list of string content. It's a practical way to write to file in Python efficiently.
By learning all these different concepts, you can leverage all the advantages of Python programming.
If you're working with structured data like tables, the `csv` module’s `writerows()` function is perfect. It allows you to write to file in Python in a tabular format, commonly used in spreadsheets and data exchange.
import csv
# Define rows of data
data = [
["Name", "Age", "City"],
["Alice", "30", "New York"],
["Bob", "25", "Los Angeles"],
["Charlie", "35", "Chicago"]
]
# Open a CSV file for writing
with open("people.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
Output:
Contents of `people.csv`:
Name,Age,City
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
Explanation:
When you're working with structured data, `writerows()` is a clean and powerful way to write to file in Python.
Each of these methods—`write()`, `writelines()`, and `writerows()`—helps you handle file writing with precision and flexibility. As you get more comfortable, you’ll find yourself choosing the right one based on your data and use case.
Do explore String formatting in Python to develop high-end applications.
A common need in many Python applications is to generate new files and store output, logs, or user-generated content. Thankfully, Python makes this straightforward with the built-in `open()` function and the appropriate file modes. In this section, we’ll walk through how to write to file in Python when you want to create a file from scratch or ensure it’s written afresh.
When using `"w"` mode, Python will create a file if it doesn’t exist or completely overwrite it if it does. This is the simplest way to write to file in Python when the contents need to be reset.
# Create or overwrite a file
with open("new_file.txt", "w") as file:
file.write("Creating a brand new file.\n")
file.write("This demonstrates the Python write file process.\n")
Output:
`new_file.txt` will be created (or overwritten) with:
Creating a brand new file.
This demonstrates the Python write file process.
Use Case: When you're sure you want to discard any previous content.
To ensure an existing file isn’t overwritten by accident, `"x"` mode helps you safely create a new file. It raises an error if the file already exists.
# Attempt exclusive creation
try:
with open("protected_file.txt", "x") as file:
file.write("This file is created only if it doesn't exist.\n")
except FileExistsError:
print("File already exists. Creation skipped.")
Output:
If a file doesn’t exist, it’ll be created, otherwise a message will be displayed.
Use Case: When protecting existing data is critical and overwriting is not allowed.
Learn about Regular Expressions in Python to easily understand every code implementation.
If the file already exists and contains valuable data, you likely want to modify it rather than overwrite it. Python supports this need with `"a"` and `"r+"` modes, both essential tools in the Python write file toolkit.
Use `"a"` mode when you want to write to file in Python without affecting the existing content. This is perfect for log files or progressive data collection.
# Append new content to an existing file
with open("log.txt", "a") as file:
file.write("New log entry added.\n")
Output:
New content is added after the existing file content. No overwriting occurs.
Use Case: Useful for audit logs, incremental saves, or running history.
To ease your Python development, learn about different Python Frameworks and Memory Management in Python.
For more advanced file edits, `"r+"` mode lets you read and write to an existing file. However, writing starts at the beginning and can overwrite content unless you manage the file pointer carefully.
# Read and write (with overwrite starting at beginning)
with open("status.txt", "r+") as file:
file.write("Status: Updated\n")
Output:
The content in the files gets updated.
Caution:
If the new content is shorter than the original, leftover text may remain.
Use Case: When you need both read and write access, such as updating headers or modifying fixed-length lines.
Additionally, to ensure all Python programs run smoothly, learn how to correctly install Python on Windows.
Text files are the most common format when working with Python, but not all data is text. Sometimes you need to write to file in Python in a way that preserves the exact byte representation—such as when working with images, audio files, executable data, or serialized objects. That’s where binary file writing comes in.
Binary files handle raw byte data. Unlike text mode, which interprets characters based on encodings like UTF-8, binary mode writes data exactly as it exists in memory. This makes it essential when you're working with non-textual or encoded content.
Also explore Speech Recognition in Python to develop next-gen applications.
To write to a binary file in Python, open the file in `"wb"` mode (write binary). This mode creates the file if it doesn't exist and overwrites it if it does.
# Define binary data (for example, image bytes or any raw byte stream)
binary_data = b'\x42\x69\x6e\x61\x72\x79\x20\x66\x69\x6c\x65\x20\x65\x78\x61\x6d\x70\x6c\x65'
# Write binary data to a file
with open("binary_output.bin", "wb") as file:
file.write(binary_data)
Output:
A file named `binary_output.bin` is created and filled with the exact bytes from `binary_data`. This file isn’t human-readable but can be read by programs expecting that byte structure.
Explanation:
Sometimes you’ll want to write binary data derived from strings or other structures. You can encode strings to bytes or serialize complex data using modules like `pickle`.
Example: Encoding a String and Writing It
# Convert a string to bytes and write it
text = "Binary mode Python write file example"
encoded_text = text.encode("utf-8")
with open("encoded_text.bin", "wb") as file:
file.write(encoded_text)
Result:
`encoded_text.bin` will contain a binary representation of the string, useful for compatibility with byte-based systems or APIs.
Example: Using `pickle` to Write Serialized Objects
import pickle
# Some Python data to serialize
data = {"username": "admin", "access": True, "id": 42}
# Write the serialized object as binary
with open("user_data.pkl", "wb") as file:
pickle.dump(data, file)
Output:
Explanation:
Binary mode is a powerful extension of the Python write file capabilities and is essential for low-level data manipulation and storage beyond plain text.
Mastering how to write to file in Python is fundamental for working with data, automating tasks, and building practical applications. From creating new files with write() to handling multiple lines with writelines() or structured data using writerows(), Python offers flexible and powerful tools for writing to files. We also explored how to safely create or modify files using various modes like "w", "a", "x", and "r+", giving you complete control over how your data is stored and preserved.
Beyond plain text, we covered how to write to a file in Python using binary mode—an essential skill for working with byte-level data such as images, encoded strings, and serialized objects. Choosing the right method and mode ensures data integrity, reduces errors, and improves the reliability of your scripts. With these techniques, you’re well-prepared to handle any file writing requirement Python throws your way.
The `write()` method in Python is used to write a string or sequence of characters to a file. When the file is opened in write mode (`"w"`), the `write()` method writes the data to the file. If the file already exists, it will be overwritten. If the file doesn’t exist, Python will create it. Keep in mind that `write()` doesn't automatically add a newline character, so it has to be explicitly included if needed.
To create a new file in Python, you can use the `open()` function with modes like `"w"` (write) or `"x"` (exclusive creation). When using `"w"`, the file is created if it doesn’t already exist, but if it does, it will be overwritten. Using `"x"` mode ensures that a new file is created only if it doesn't exist already; otherwise, it raises a `FileExistsError`. Always handle these situations carefully to prevent unintentional data loss.
Yes, you can write multiple lines to a file using the `writelines()` method. It takes a list or iterable of strings and writes each one to the file sequentially. However, `writelines()` does not automatically insert line breaks between the lines, so you need to include `\n` (newline) characters within each string if you want separate lines. This method is often faster for writing large numbers of lines compared to writing them one by one with `write()`.
To append data to an existing file, you can open the file in append mode (`"a"`). In this mode, Python will add new content to the end of the file without modifying the existing data. If the file doesn’t exist, it will be created. The `"a"` mode is ideal for situations where you don’t want to overwrite any existing content, such as when adding log entries or adding incremental data.
The `write()` method writes a single string to the file, while `writelines()` writes a sequence of strings, typically from a list or iterable. The main difference is that `write()` writes one string at a time, and it does not automatically add newlines (`\n`) between strings, which means you must include them if needed. On the other hand, `writelines()` can write multiple lines in one call, but it also doesn’t add newline characters, so you need to handle them manually.
Reading from a file in Python can be done using the `open()` function with modes like `"r"` (read), `"r+"` (read/write), or others. After opening the file, you can use methods like `read()` to get the entire content, `readline()` to read one line at a time, or `readlines()` to get a list of all lines in the file. Always close the file after reading to free system resources, or use the `with` statement to ensure the file is automatically closed after the operation.
The `"w"` mode in Python is used when you want to open a file for writing. If the file doesn’t already exist, Python creates it. However, if the file already exists, opening it in `"w"` mode will overwrite its contents. This mode is ideal for creating or replacing files but be cautious because it will erase any pre-existing data. For scenarios where you don’t want to overwrite an existing file, other modes like `"a"` or `"x"` should be considered.
To write binary data in Python, you should open the file in binary write mode (`"wb"`). Binary data is represented as `bytes` objects, which are collections of raw bytes. When writing binary data, Python will write the exact byte sequence to the file without interpreting it as text. This mode is commonly used for files like images, videos, or other non-text data formats. Ensure you're dealing with binary-compatible data before using this method to avoid errors.
If you attempt to write to a read-only file in Python, you will encounter a `PermissionError`. This error happens because the file's permissions do not allow writing. To resolve this issue, you must change the file permissions or choose a different file that has write permissions. You can also use a try-except block to catch the exception and handle the error gracefully, allowing the program to continue without crashing.
To handle errors when writing to files in Python, use a `try-except` block around the file operations. Common errors include `FileNotFoundError` if the file doesn’t exist or `PermissionError` if the file is read-only. You can catch these exceptions and take action, such as notifying the user, retrying the operation, or creating the file if it doesn’t exist. Using error handling ensures your program doesn’t crash unexpectedly and can respond to unexpected situations.
Yes, you can write to a file without overwriting its existing content by opening the file in append mode (`"a"`). This mode adds new data to the end of the file, leaving the current content intact. It’s a great option when logging information or adding new data incrementally. If the file doesn’t exist, it will be created. Just remember, while this mode is safe for appending data, it doesn't give you control over where in the file the data is written.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.