How to Write File in Python
In this tutorial, we will learn how to write a file in Python with the help of examples. In Python or any other programming languages, writing and reading are two basic operations in the file handling.
Writing files is a basic and crucial aspect of programming. It allows us to save data permanently, share information between different programs, or log events. Let’s understand how to writing a file step by step.
Opening a File in Python
The first step to writing a file in Python is to open it in write ‘w’, append ‘a’, or exclusive creation ‘x’ mode. This is done using the open() function, which returns a file object whose type is file. We can use this file object to refer to a file on disk storage. The general syntax to open a file in Python using open() function is as:
openfile = open("file_name", "access_mode", bufferring = -1)
Here, the open() function takes three parameters: file_name, access_mode, and buffering.
- The first parameter is a file_name which represents the name of a file that has to be opened.
- The second parameter is an access_mode that specifies the mode in which the file will be opened. With the help of this parameter, we can control what kind of operations we want to perform on a file. However, this is an optional parameter.
- The third parameter is a buffering, which is also an optional integer parameter used to set the buffering policy. It specifies the buffer size of a file. If the value of buffer size is set to 0, it means no buffering takes place. On setting value 1, line buffering is performed. If the value is set to any positive number other than 1, buffering is performed according to the buffer size mentioned.
- A negative buffer size indicates to use system default. If we omit it, the system default will be used.
Let’s take an example in which we will open a file in write mode.
Example 1:
# Open a file in writing mode.
openfile = open("test.txt", "w")
Once a file is opened in write mode, we can write to it. Let’s understand various methods of writing data into a text file.
Ways to Write Data in a Text File in Python
There are three different ways by which we can write data into a text file in Python. They are as:
- write()
- writeline()
- writerow()
Writing Text File using write() Function
The simplest way to write to a file in Python is by using the write() function. This function writes data to an open file by overwriting the previously present data or information. The syntax of write() function is as follows:
write(string)
Here, the write() function takes any string or sequence of bytes (for binary files) as an argument and returns the number of characters written to the file. The write() function does not add a newline character (‘\n’) to the end of the string.
Let’s take a simple example program in which we will write five friend names into a file named “friends.txt”. We will first open the file using the open() function and then write to it. Here’s a basic code:
Example 1:
# Python program to perform write() function operation.
fileName = "friends.txt" # text file is assigned.
# Open a file in write mode using open() function.
openfile = open(fileName, "w")
if not openfile:
print("File does not created.")
else:
# Writing friend names into a file using file object (openfile).
openfile.write("Tripti\n")
openfile.write("Mahi\n")
openfile.write("Ivaan\n")
openfile.write("Rashmi\n")
openfile.write("Amit\n")
# Now close the opened file.
openfile.close()
print("File", openfile.name, "successfully closed.")
Output: File friends.txt successfully closed.
When you will execute this program, a text file named “friends.txt” is created in the same folder “C:\Python Project\FileHandling\friends.txt” where you have stored your program. You can read the content of the file in any text editor software like Notepad, MS-word, WordPad, etc. for reading ASCII files. If we open the file in Notepad, the content of the file will look like as shown in the figure.
Let’s take an example in which we will create a file to write the first 5 natural numbers into a file named num.txt.
Example 2:
openfile = open("num.txt", 'w')
if not openfile:
print("File is not created!!")
else:
for i in range(1, 6):
openfile.write(str(i) + '\n')
openfile.close()
Data written to a text file is as:
1 2 3 4 5
In this example, the line openfile.write(str(i) + ‘\n’) writes the natural numbers from 1 to 5 as ASCII text format in separate lines in the num.txt file. If we omit a newline character (‘\n’), it will write all numbers in one line.
Using with Statement to Write to a File
We can also write the above example 1 using with statement as given below:
fileName = "friends.txt" # text file is assigned.
# Open a file in write mode.
with open(fileName, "w") as openfile:
if not openfile:
print("File does not created.")
else:
# Writing friend names into a file using file object (openfile).
openfile.write("Tripti\n")
openfile.write("Mahi\n")
openfile.write("Ivaan\n")
openfile.write("Rashmi\n")
openfile.write("Amit\n")
print("File", openfile.name, "closed.")
Now it is important to note that we have not used close() function to close the file because the with statement opens a file and automatically closes the file when it completes the with block.
How to Write Multiple Lines in a File in Python?
To write multiple lines, Python provides to use a built-in writelines() function. The writelines() function in Python writes a list of strings or list of lines to a file at a time. This function is especially useful when we have multiple items, such as lines of text, and we want to write to a file in one go, rather than using the write() method multiple times.
The basic syntax for this function is as follows:
writelines(iterable)
In the above syntax, the writelines() function takes an iterable object (like a list or a tuple) in string form and writes each string to the file. Importantly, writelines() function does not add a newline character (\n) between the items. So, you have to include them in the strings if you want the text to appear on separate lines in the file.
Let’s take an example program in which we will write multiple lines of text into a file using writelines() function
Example 3:
# Python program to perform writelines() function operation.
# List of strings.
lines = ["First line\n", "Second line\n", "Third line\n", "Fourth line\n"]
# Open the file in write mode using with statement.
with open("example.txt", "w") as file:
# Write the lines to the file
file.writelines(lines)
When we will run this program, we will get the following output in the text editor like Notepad.
Output: First line Second line Third line Fourth line
In this example, we have used a newline character (‘\n’) at the end of each string to appear on the separate lines in the file. This is because
the writelines() function does not automatically insert a newline character (\n) between the strings, so you need to include them yourself if required.
Remember, if you pass a non-string iterable, it will raise a TypeError exception. It’s a good practice to use writelines() function within a with statement, which takes care of opening and closing the file for you. Therefore, this function can be more efficient than repeatedly calling write(), especially when dealing with lists of text.
Writing Binary Files in Python
For writing in binary files, such as images or executable files, open the file in ‘wb’ (or ‘w + b’) mode. Here, the ‘w’ means that we are writing to the file and ‘b’ refers to the binary mode. In this mode, data is written in bytes.
Here’s a simple Python program that writes the first 10 natural integer numbers to a file in binary format. This example will create a file and write the integers 1 through 10 to it, each as a binary byte.
Example 4:
# Python program to perform the write operation in the binary format.
# This statement will open a file in binary write mode.
with open("numbers.bin", "wb") as file:
# Write the first 10 natural integer numbers 1 through 10 to the file in binary format.
for number in range(1, 11):
file.write(number.to_bytes(1, byteorder='big'))
print("Integers written to numbers.bin in binary format.")
Output: Integers written to numbers.bin in binary format.
In this example program, the file numbers.bin is opened in binary write mode (‘wb’). The range(1, 11) generates the first 10 natural numbers from 1 to 10. The to_bytes(1, byteorder = ‘big’) function converts each number to a bytes object of length 1 byte using big-endian byte order. Each byte is written into the file using the write() method.
When we will run this program, it will create a file named numbers.bin and write the numbers 1 through 10 into it in binary format. Each number is stored as a single byte. The binary file created contains some garbled values which are not human readable form.
How to Write a CSV File in Python?
Writing a CSV (Comma Separated Values) file in Python is straightforward. We can efficiently handle it using Python’s built-in csv module. First, we need to import it into the program. This module provides a writerow() function for reading and writing into csv files. The writerow() function takes a list and writes them into a csv file.
Below is an example Python program that demonstrates how to write data to a CSV file. In this example, we will create a CSV file named example.csv and write a few rows of data to it.
Example 5:
# Python program to perform the write operation into a csv file.
# Import csv module.
import csv
# Data to be written to the CSV file
data = [
["Name", "Age", "City"],
["Alice", 28, "New York"],
["Bob", 22, "Los Angeles"],
["Charlie", 30, "Chicago"]
]
# Open the file in write mode.
with open("example.csv", "w", newline='') as file:
writer = csv.writer(file)
# Write each row to the CSV file
for row in data:
writer.writerow(row)
print("Data written to example.csv successfully.")
In this example program, first we have imported the csv module. Then, we have created a data list that contains rows of data to be written into the CSV file, including the header row. After that, we have opened example.csv file in the write mode. The newline=” argument is used to prevent adding extra newline characters in the output on some platforms.
We have created a csv.writer object, which is used to write data to the CSV file. We iterated over each row in the data list and wrote it to the file using writer.writerow(row).
When we run this program, it will create a file named example.csv and write the header and data rows into it. The resulting CSV file will look like this:
Output: Data written to example.csv successfully.
Data written to the example.csv file is as follows:
Name, Age, City Alice, 28, New York Bob, 22, Los Angeles Charlie, 30, Chicago
Key Points to Write a File in Python
Here, we have explained the following key points that you should keep in mind to write a file in Python. They are as:
- Open a file in a specific mode using a built-in open() function before writing to a file.
- After opening the file, you can write text or data to it using write() or writelines() function.
- Close the file using close() function after you’re done writing. This is necessary to free up resources and ensure all data is properly written to the file.
- Use with statement to open a file which automatically takes care of closing the file, even if an error occurs.
Python provides multiple ways to write to files, each suitable for different scenarios. Whether you’re working with text, binary, or CSV file, Python provides a standard library to handle it. Hope that you will have understood the basic concepts of writing a file in Python and practiced all example programs.
Thanks for reading!!!