Skip to content

text file

In Python, a text file is a file object that reads and writes strings, handling the text encoding automatically. Usually it’s a file on disk that stores plain text in a human-readable format, but sys.stdin, sys.stdout, and io.StringIO instances count as text files too.

Python provides several tools, functions, and modules for working with text files. When you open a text file, you can read from it, write to it, or append new content. Text files are a simple yet powerful way to persist data, making them a common choice for configuration files, logs, and other use cases where human readability is essential.

Using the built-in open() function, you can open a text file in different modes, such as read ("r"), write ("w"), append ("a"), and more. Unlike binary files, they use standard character encodings like ASCII or UTF-8 to represent information in a way that’s immediately readable by people.

Example

Here’s an example of how to read from and write to a text file in Python:

Language: Python
>>> # Writing to a text file
>>> with open("example.txt", mode="w", encoding="utf-8") as file:
...     file.write("Hello, Pythonista!")
...
18

>>> # Reading from a text file
>>> with open("example.txt", mode="r", encoding="utf-8") as file:
...     content = file.read()
...

>>> content
'Hello, Pythonista!'

This code snippet demonstrates how to create a text file called example.txt, write a line of text to it, and then read the content back and print it to the screen.

Note that the .write() method returns the number of characters written to the file, which is 18 in this example. Specifying encoding="utf-8" when you open the file is a good habit because it makes your code behave consistently across platforms instead of relying on the locale’s default encoding.

The locale-dependent default is on its way out: PEP 686 is Final and Python 3.15 turns UTF-8 mode on by default, so open() will use UTF-8 unless you say otherwise. Passing the encoding explicitly still keeps your intent clear and your code correct on older versions.

Reading and Writing Files in Python (Guide)

Tutorial

Reading and Writing Files in Python (Guide)

In this tutorial, you'll learn about reading and writing files in Python. You'll cover everything from what a file is made up of to which libraries can help you along that way. You'll also take a look at some basic scenarios of file usage as well as some advanced techniques.

intermediate python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Sept. 27, 2026 • Reviewed by Dan Bader