How to write to file in python
How to write to file in python
How to Write to a Text File in Python
Artturi Jalli
In Python, you can write to a text file by following these three steps:
You can skip the last step by using the with statement.
This piece of code creates a new file called example.txt and writes “Hello World” into it.
In this guide, you are going to learn the basics of writing to a file in Python.
Python How to Write to a File in Detail
To write to a file in Python, use these three steps:
The syntax for the open() function is as follows:
The open() function returns a file object. This file object has two useful methods for writing text to the file:
Let’s see how to use these file writing methods.
The write() Method in Python
The write() method takes a string argument. It writes this argument into the opened file.
For example, let’s create a list of strings and use the write() method to write each of the strings into the file using a for loop:
As a result, a file called example.txt is created with the following content:
Notice how each string is written to the same line by default.
If you want to have each word appear on a separate line, write the line break character ‘\n’ after writing a string to the file.
In the example.txt file the result looks like this:
This is one way to write into a file.
But in the case of multiple strings, you can use the writelines() method to write them all into a file on the same go.
The writelines() Method in Python
The writelines() function takes an iterable object, such as a list, that contains strings to be written into the opened file.
For example, let’s repeat the above example using the writelines() method:
After running this piece of code, the example.txt file looks like this:
Now you know how to write text to a file in Python.
Next, let’s take a look at how to add text at the end of an already existing text file.
How to Append to a File in Python
To add text at the end of a file after the existing lines of text, use the write mode ‘a’.
This mode is called the appending mode. Appending means adding to the end of something.
Here the result is a file called example2.txt with the following contents:
As you can see, the last bits of text were successfully added to the end of the text file.
Conclusion
Today you learned how to write to a file in Python.
To recap, to write to a file, follow these three steps:
Python Write Text File
Summary: in this tutorial, you’ll learn various ways to write text files in Python.
The following illustrates how to write a string to a text file:
Steps for writing to text files
To write to a text file in Python, you follow these steps:
The following shows the basic syntax of the open() function:
The open() function accepts many parameters. But you’ll focus on the first two:
For writing to a text file, you use one of the following modes:
Mode | Description |
---|---|
‘w’ | Open a text file for writing. If the file exists, the function will truncate all the contents as soon as you open it. If the file doesn’t exist, the function creates a new file. |
‘a’ | Open a text file for appending text. If the file exists, the function append contents at the end of the file. |
‘+’ | Open a text file for updating (both reading & writing). |
The writelines() method accepts an iterable object, not just a list, so you can pass a tuple of strings, a set of strings, etc., to the writelines() method.
To write a line to a text file, you need to manually add a new line character:
Writing text file examples
The following example shows how to use the write() function to write a list of texts to a text file:
If the readme.txt file doesn’t exist, the open() function will create a new file.
The following shows how to write a list of text strings to a text file:
If you treat each element of the list as a line, you need to concatenate it with the newline character like this:
Appending text files
To append to a text file, you need to open the text file for appending mode. The following example appends new lines to the readme.txt file:
Writing to a UTF-8 text file
If you write UTF-8 characters to a text file using the code from the previous examples, you’ll get an error like this:
To open a file and write UTF-8 characters to a file, you need to pass the encoding=’utf-8′ parameter to the open() function.
The following example shows how to write UTF-8 characters to a text file:
How to Write to File in Python
With Python, you can modify and write directly to a file programmatically, saving you the hassle of doing it manually. In this article, you will learn how to write to a file in Python.
Before diving into the nitty-gritty of how to write to file in Python, I want to mention that I use Python 3.8.5 and Windows 10. However, your results should be the same on any operating system.
It’s good to have some knowledge of file manipulation before you read this article. For more information, read How to Work with Files and Directories in Python and How to Rename Files with Python.
There are multiple ways to write to files and to write data in Python. Let’s start with the write() method.
Use write() to Write to File in Python
However, with this method, you need to close the file yourself by calling the close() method:
It is shorter to use the with statement, as we do not need to call the close() method.
This is the method we’ll use in this tutorial:
We can then call the write() method to modify our file programmatically.
Let’s run an example:
Once this command has been executed, we want to read the file to see if it has been updated. We need to call the read() method, as shown below:
It’s important to note that the parameters in the open() function will decide where the write() method will be active.
If you want to learn more on how to write files in Python with the write() method, check out our course on Working with Files and Directories in Python.
Use writelines() to Add List Data to a File
After checking the output, you will notice that writelines() does not add any line separators by default; we have to specify the line separator. We can modify our code with the following:
A more Pythonic and efficient way of doing it is:
The code above will use new lines as the line separator.
Writing Data to CSV Files in Python
You might find it useful to be able to update a CSV file directly with Python.
CSV stands for comma-separated values. If you are a data professional, you’ve certainly come across this kind of file. A CSV file is a plain text file containing a list of data. This type of file is often used to exchange data between applications. If you want to refresh your knowledge of CSV files, read our article How to Read CSV Files in Python.
In this part, we will use Python’s built-in csv module to update a CSV file.
When you want to write data to a file in Python, you’ll probably want to add one or more rows at once. The data can be stored in lists or a dictionary. Let’s explore some ways to write data to files in Python.
Writing List Data to a CSV
Use writerow() for a Single Row
To write in a CSV file, we need to open the file, create a writer object and update the file. Let’s run an example:
For detailed information, it’s always a good idea to read the documentation.
Now, let’s explore how to write data in Python when you need to add multiple rows of data.
Use writerows() for Multiple Rows
We can write multiple rows to a file using the writerows() method:
We just added several rows to our file.
You can find more information about the writerows() method in the documentation.
Writing Dictionary Data to a CSV
If each row of the CSV file is a dictionary, you can update that file using the csv module’s dictWriter() function. For example:
And that’s all you have to do!
If you want to learn more on the topic, do not forget to check the course on working with files and directories in Python.
Using pathlib to Write Files in Python
Now let’s explore using the pathlib module to write to a file in Python. If you are not familiar with pathlib, see my previous article on file renaming with Python.
It is important to note that pathlib has greater portability between operating systems and is therefore preferred.
Use write_text()
We can use the Path().write_text() method from pathlib to write text to a file.
The is_file() function will return a Boolean value that’s True if the path points to a regular file and False if it does not. The with_name() function will return a new path with the changed filename. Finally, with_suffix() will create a new path with a new file extension.
You can read about the details of these methods in the Python documentation.
Let’s run an example that demonstrates all this. We will open our text file, write some text, rename the file, and save it as a CSV file.
File Manipulation in Python
In this final part, we will explore file manipulation in Python using the tell() and seek() methods.
Use tell() to Get the Current Position
The tell() method can be used to get the current position of the file handle in the file.
It helps to determine from where data will be read or written in the file in terms of bytes from the beginning of the file.
You can think of the file handle as a cursor that defines where the data is read or written in the file. This method takes no parameter and returns an integer.
Let’s run an example:
You can find more information in the Python documentation.
Use seek() to Change Stream Positions
The seek() method is used to change the stream position. A stream is a sequence of data elements made available over time, and the stream position refers to the position of the pointer in the file.
The seek() method is useful if you need to read or write from a specific portion of the file. The syntax is:
What does this mean?
If you omit the whence parameter, the default value is 0.
When we open the file, the position is the beginning of the file. As we work with it, the position advances.
The seek() function is useful when we need to walk along an open file. Let’s run a quick example:
You can find more information in the Python documentation.
Learn More About Working with Files in Python
We covered a lot of ground in this article. You’re getting some solid knowledge about file manipulation with Python.
Now you know how to write to a file in Python and how to write data to a file in Python. We also briefly explored the tell() and seek() methods to manipulate a file.
Don’t forget to check our course on Working with Files and Directories in Python to deepen and solidify your Python knowledge!
Python Write Text File
Table of Contents Hide
Python provides built-in functions to perform file operations, such as creating, reading, and writing files. There are mainly two types of files that Python can handle, normal text files and binary files. In this tutorial, we will look at how to write content into text files in Python.
Steps on How to write to a File in Python
In order to write to a text file in Python, you need to follow the below steps.
Step 1: The file needs to be opened for writing using the open() method and pass a file path to the function.
Step 3: Once the write operation is performed, the text file must be closed using the close() function.
Now that we have seen the steps to write to a text file let’s understand each of these methods before getting into examples.
Python open() function
The open() function opens the file if possible and returns the corresponding file object.
Syntax – open(file, mode=’w’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
The open() function has a lot of parameters. Let’s take a look at the necessary params for writing to a text file. It opens the file in a specified mode and returns a file object.
Example
Methods for Writing to a text file in Python
Python close() function
The file will remain open until you close the file using the close() function. It is a must and best practice to perform this operation after writing the data into the file as it frees up the memory space acquired by that file. Otherwise, it may cause an unhandled exception.
We can use the with statement, which helps to close the file once the write operation is performed. We don’t have to specify any explicit close method everytime.
Examples for Writing to Text file in Python
Example 1 – Write a line to a text file using the write() function
Let’s look at writing a line into a text file using the write() method. We will use the with statement, which helps to close the file once the write operation is performed. We don’t have to specify any explicit close method.
Output
Example 2 – Append a line to a text file using the write() function
If you want to append the line to the existing text file, you need to open the file in the append mode first and perform the write() operation, as shown below.
Output
Example 3 – Write a list to a file using the writelines() function
Let’s look at writing multiple lines into a text file using the writelines() method. The writelines() method accepts an iterable object such as list, set, tuple, etc. In the below example let’s see how to write a list to a file in Python
Syntax of writelines()
file.writelines(list)
Parameters
list – The list of texts or byte objects that will be inserted. It can be a list, tuple, set of strings, etc.
Output
report this ad
Example 4 – Append multiple lines to a text file using the writelines() function
If you want to append multiple lines to the existing text file, you need to open the file in the append mode first and perform the writelines() operation, as shown below.
Writing to file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s).
Note: To know more about file handling click here.
Access mode
Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. Different access modes for reading a file are –
Note: To know more about access mode click here.
Opening a File
It is done using the open() function. No module is required to be imported for this function.
Syntax:
The file should exist in the same directory as the python program file else, full address of the file should be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For example, if there is \temp in the file address, then \t is treated as the tab character and error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in same directory and address is not being placed.