- Python Write Text File
- Steps on How to write to a File in Python
- Python open() function
- Methods for Writing to a text file in Python
- Python close() function
- Examples for Writing to Text file in Python
- Example 1 – Write a line to a text file using the write() function
- Example 2 – Append a line to a text file using the write() function
- Example 3 – Write a list to a file using the writelines() function
- Example 4 – Append multiple lines to a text file using the writelines() function
- How to Use Python to Write a Text File (.txt)
- How to Use Python to Write to a Text File
- Writing Multiple Lines to a Text File Using Python
- How to Append to a Text File in Python
- How to Write UTF-8 Encoded Text to a File in Python
- Conclusion
- Additional Resources
Python Write Text File
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 2: The next step is to write to file, and this can be achieved using several built-in methods such as write() , writelines() .
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.
- file – path like object which represents the file path
- mode (Optional) – The mode is an optional parameter. It’s a string that specifies the mode in which you want to open the file.
Methods for Writing to a text file in Python
- write() : The write() function will write a line to a text file. It inserts a single line in the text file.
- writelines() : The writelines() function will write multiple string lines at once to a text file. The writelines() method accepts an iterable object such as list, set, tuple, etc.
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.
# Program to write to text file using write() function with open("python.txt", "w") as file: content = "Hello, Welcome to Python Tutorial !! \n" file.write(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello, Welcome to Python Tutorial !!
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.
# Program to append to text file using write() function with open("python.txt", "a") as file: content = "Append the content at the end \n" file.write(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello, Welcome to Python Tutorial !! Append the content at the end
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)
list – The list of texts or byte objects that will be inserted. It can be a list, tuple, set of strings, etc.
# Program to write multiple lines to text file using writelines() function with open("python.txt", "w") as file: content = ["Hello\n", "Welcome to Python Tutorial\n", "Cheers \n" ] file.writelines(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello Welcome to Python Tutorial Cheers
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.
# Program to append to text file using writelines() function with open("python.txt", "a") as file: content = ["Appending the content\n", "Python\n" ] file.writelines(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello Welcome to Python Tutorial Cheers Appending the content Python
How to Use Python to Write a Text File (.txt)
In this tutorial, you’ll learn how to use Python to write (or save) to a text file. Python provides incredible opportunity to read and work with text files – being able to save the output to a text file is an important skill. Python can handle both regular text files and binary files – in this tutorial, you’ll learn how to work with text files.
By the end of this tutorial, you’ll have learned:
- How to use Python to write to a .txt file
- How to use a context manager to safely write to a text file
- How to append text to a file in Python
- How to write UTF-8 text to a File in Python
How to Use Python to Write to a Text File
Python provides a number of ways to write text to a file, depending on how many lines you’re writing:
- .write() will write a single line to a file
- .writelines() will write multiple lines to a file
These methods allow you to write either a single line at a time or write multiple lines to an opened file. While Python allows you to open a file using the open() , it’s best to use a context manager to more efficiently and safely handle closing the file.
Let’s see what this looks like:
# Writing a Single Line to a Text File text = 'Welcome to datagy.io!' with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: f.write(text)
Let’s break down what the code above is doing:
- We load a string that holds our text in a variable text
- We then use a context manager to open a file in ‘w’ mode, which allows us to overwrite an existing text
- The file doesn’t need to exist – if it doesn’t, it’ll automatically be created
- When then use the .write() method to write our string to the file
Writing Multiple Lines to a Text File Using Python
In many cases, you may not want to write a single line of text to a file. Let’s take a look at how we can write multiple lines of text to a file using the .write() method:
# Writing Multiple Lines to a Text File text = ['Welcome to datagy.io!', "Let's learn some Python!"] with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: for line in text: f.write(line) f.write('\n')
Let’s take a look at what we’re doing in the code above:
- We load a list of strings that contains the lines of text we want to save
- Similar to the previous example, we open the file using a context manager
- We then loop over each item in the list to write each string to the file
- For each item, we also write a newline character so that each line is split across a new line
The approach above feels a bit clunky. We can simplify this process by using the .writelines() method, which allows us to write multiple lines at once. Let’s see how we can modify our code above to use the .writelines() method:
# Writing Multiple Lines to a Text File (with .writelines) text = ['Welcome to datagy.io', "Let's learn some Python!"] with open('/Users/nikpi/Desktop/textfile.txt', 'w') as f: f.writelines('\n'.join(text))
In the code above, we avoid using a for loop to write multiple lines of text to a file. Because our text isn’t separated by newline characters, we use the .join() string method to place each item onto a new line.
How to Append to a Text File in Python
In the previous sections, you learned how to write a new file with text in Python. In this section, you’ll learn how to append to a given text file using Python. We previously used the write mode, ‘w’ when opening the file – in order to append, we use the append mode, ‘a’ .
Let’s see how we can append to a text file in Python:
# Appending to a Text File in Python text = 'Welcome to datagy.io!\n' with open('/Users/nikpi/Desktop/textfile.txt', 'a') as f: f.write(text)
Running this will append to the end of the text file. Note that we applied the newline character into the string. This could also be done in the context manager, depending on how you prefer your code to run.
Similarly, we can append multiple lines to a file by using the .writelines() method, as shown below:
# Appending Multiple Lines to a Text File text = ['Welcome to datagy.io!\n', 'Python is fun!\n'] with open('/Users/nikpi/Desktop/textfile.txt', 'a') as f: f.writelines(text)
How to Write UTF-8 Encoded Text to a File in Python
Python will open a file using the system’s default encoding. While UTF-8 is the de-facto standard, your system may not open the file using that encoding format. Because of this, you may need to specify the encoding format when opening the file.
Let’s see how we can do this:
# Specifying Encoding to UTF-8 text = 'é' with open('/Users/nikpi/Desktop/textfile.txt', 'w', encoding="utf-8") as f: f.write(text)
Running this code on, for example, macOS, doesn’t require specifying the encoding. However, if you want your code to run platform independently, it is a good idea to specify the encoding.
Conclusion
In this tutorial, you learned how to use Python to write a text file. You first learned about the different ways of overwriting a file using the .write() and .writelines() methods. You learned about the nuances of inserting newline characters. Then, you learned how to append to an existing file, both single lines as well as multiple lines. Finally, you learned how to specify the encoding when writing a file.
Additional Resources
To learn more about related topics, check out the tutorials below: