Text File
In Python, a text file is a type of computer file that contains plain text. It typically stores information in a human-readable format, like a sequence of characters representing text.
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:
>>> # Writing to a text file
>>> with open("example.txt", mode="w") as file:
... file.write("Hello, Pythonista!")
...
18
>>> # Reading from a text file
>>> with open("example.txt", mode="r") 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.
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Why Is It Important to Close Files in Python? (Tutorial)
- Context Managers and Python's with Statement (Tutorial)
- Reading and Writing Files in Python (Course)
- Reading and Writing Files in Python (Quiz)
- Python's Built-in Functions: A Complete Exploration (Quiz)
- Context Managers and Using Python's with Statement (Course)
- Context Managers and Python's with Statement (Quiz)