How to Read a Text File in Python?

How-to-Read-a-Text-File-in-Python-Feature-2.jpg

Reading and writing text files is an important operation when working with files in Python. They help store information for future use. Python makes file handling easy by offering many built-in functions. These operations are essential for many practical tasks, such as saving user input, processing the log files, and creating reports. Reading and writing files allow programs to store and retrieve data even after they stop running. In this blog, you’ll explore various methods for reading and writing text files in Python, complete with detailed examples.

Table of Contents:

What is File Handling in Python?

File handling in Python means managing files on your computer. With file handling, you can open, read, write, append, update, or delete file contents. This can be useful when you want to save information for later use. For example, if you write a student marks calculator program, you can store the details in a file. Later, you can open the file to retrieve the saved data, even if the program has been closed. Python includes built-in functions for handling files. You just need to know how to open a file correctly, choose the appropriate mode, read or write data, and close the file when done.

File Modes in Python

File modes inform Python what you are going to do with the file. When you open a file in Python, you have to provide a mode based on whether you want to read from it, write to it, or append some data.

Below are the common file modes in Python:

Mode Description
r (Read mode) Opens the file for reading only. The file must exist, or an error will occur.
w (Write mode) Opens the file for writing. Clears content if the file exists; creates a new file if it doesn’t.
a (Append mode) Opens the file to add content at the end. Keeps existing data unchanged.
x (Exclusive creation mode) Creates a new file and opens it for writing. Raises an error if the file already exists.
b (Binary mode) Used for binary files like images, videos, or executables.
t (Text mode) Default mode used for reading and writing plain text files.
r+ (Read and write mode) Opens the file for both reading and writing. Gives an error if the file does not exist.
a+ (Append and read mode) Opens the file for reading and appending. Adds new data at the end. Creates the file if it doesn’t exist.
Unlock Python: Power Up Your Programming Skills!
Dive into real-world coding projects and become confident in writing clean, efficient Python code.
quiz-icon

Reading from a Text File in Python

Reading a text file in Python means using the saved data in your program to show or work with it. You can read one line or the whole file. But before reading, it is important to know how to make and open the file the right way. These simple steps help avoid errors and make your code cleaner.

Procedure to Create a New Text File in Python

The first step before you read or store data is to create a new text file. In Python, there is a built-in function that will create a new text file easily.

Using the create mode “x” to create a new file

To create a new text file in Python, you will use the open() function with the create mode “x”. This will create a file, but raises an error if the file already exists.

Python
New Text File in Python

Explanation: Here, a file named freshfile.txt is created, and one line of text is written into it using the write mode.

Methods to Read a File in Python

After creating and opening a file in read mode, Python allows you to read a file’s contents using three main methods. You may read the entire file at once, one line at a time, or all of the lines together as a list. The appropriate reading method for your file will depend on your needs and the size of the file.

Let’s explore the three ways for reading text files with the help of examples from the Intellipaat course list, which is saved as a text file.

Assuming a file named courses.txt has:

Python for Data Science
Machine Learning with Python
Data Analytics with Excel
Cloud Computing with AWS

1. Using read() Method in Python

The read() operation is used to read the entire content of a file in one go and returns it as a single continuous string, making it ideal for smaller files.

Example:

Python
using the read method

Explanation: Here, the full list of Intellipaat courses has been read and printed as a block of text.

2. Using readline() Method in Python

The readline() method helps in reading one line at a time from a text file, making it useful for processing files line by line in a memory-efficient way.

Example:

Python
readline() Method in Python

Explanation: Here, the first two course names are read and printed one at a time. This is helpful if you want to read a certain number of lines, or if you want to only read some lines based on a condition.

3. Using readlines() Method in Python

The readlines() method in Python reads all lines from a file and returns them as a list of strings, with each string representing a line, including newline characters.

Example: 

Python
using readlines method in python

Explanation: Here, the strip() function is used to remove trailing spaces and newline characters from each line before printing, ensuring clean and formatted output.

Get 100% Hike!

Master Most in Demand Skills Now!

Writing to a Text File in Python

In Python, you can write data to a text file using the open() method with the correct access mode. The “w” (write) mode creates a new file or overwrites an existing one, while the “a” (append) mode adds data to the end of an existing file without affecting its current contents. Append mode is especially useful when maintaining log files, saving course details, or storing user-inputted data. Always ensure the file is properly closed after writing to avoid data loss or file corruption.

Methods to Write to a File in Python

For writing to a file, Python provides flexible options. Python allows writing a single string at a time or all strings in a list at once. It depends on the structure of the data, which is the correct option, and whether you are appending to a file, replacing it, etc.

1. Using the write() Method in Python

The writelines() method lets you write multiple strings from a list to a file at once. However, it does not insert newline characters automatically, so each string in the list must already include n if you want the content to appear on separate lines.

Example: 

Python

Output:

write() Method in Python

Explanation: Here, the file course_info.txt is created (or modified if it already exists), and three separate lines of course-related information are written using write().

2. Using the writelines() Method in Python

The write() method is used to write a single string to a file. It does not add a newline automatically, so if you want the text to appear on a new line, you need to include n manually in the string.

Example: 

Python

Output:

writelines method in python

Explanation: Here, a list of course names from Intellipaat gets written using the writelines() method to course_list.txt.

3. Using a for Loop with write() in Python

Using a for loop with the write() method lets you write multiple formatted lines to a file, making it useful when working with structured or repeated data.

Example: 

Python

Output:

using for loop in python

Explanation: Here, each of the course names is iterated over and written to the file course_modules.txt with matched formatting for each line.

Common Errors While Reading and Writing a Text File in Python

  1. FileNotFoundError: A FileNotFoundError is the error message that Python displays when it cannot find the file located at the given path. To avoid this error, you should check that the path and name are strings correctly, and also check that the file exists first before opening the file using os.path.exists(). 
  2. Reading or Writing a Closed File: If you try to read from a closed file or if you try to write to a closed file, you can get an error. You will always want to use ‘with open(…)’ so your program can open and close your file safely. 
  3. Missing Encoding Parameter: If you write non-ASCII characters without specifying the encoding, you may encounter encoding errors. To handle special characters correctly, use the encoding=”utf-8″ parameter with the open() function.
  4. Data Overwrite Problems: You might accidentally use “w” mode to open your file, which will delete any previous data in the file. If you want to keep the data that is already in your file, you should use “a” for append, or check to see if the file contains data before writing.

Best Practices for Reading and Writing a Text File in Python

  1. Always use the with statement: You should always use with open() because this will ensure the file closes after reading or writing, regardless of whether something went wrong in your program.
  2. Use the correct file mode: Use the correct file mode, reading or writing, such as ‘r’ for reading and ‘w’ for writing, so that you do not lose data or access data that you did not intend to.
  3. Be careful with encodings: Always include encoding=’utf-8′ so that you can have any special characters and avoid decoding and encoding issues. This is especially true if your text files might have been generated on different systems.
  4. Read and write efficiently: If your files are very large, try reading from the file or writing to the file one line at a time, instead of loading all the data into memory, to avoid running out of memory.
Start Coding in Python for Free: No Experience Needed!
Begin writing real Python code through interactive, beginner-friendly modules—completely free.
quiz-icon

Conclusion

Proper file handling in Python is vital to writing clean and robust code. File handling in Python gives you the flexibility to efficiently read from and write to text files with simple commands. Being aware of file modes and encodings also helps to prevent common mistakes. Using best practices such as the with statement makes file access safer. It helps to write cleaner code and decrease the likelihood of undesired failures. With consistent experience in file handling, you will feel the task is effortless when writing Python scripts.

Take your skills to the next level by enrolling in the Python Course today and gaining hands-on experience. Also, prepare for job interviews with Python Interview Questions prepared by industry experts.

How to Read a Text File in Python? – FAQs

Q1. How do I open a text file in Python

You can open a text file in Python with the help of a file name and by using a mode like read, write, or append.

Q2. What are the different ways to read a text file in Python?

Text files can be read using read(), readline(), and readlines() methods in Python.

Q3. How can I write multiple lines to a file

To write multiple lines to a file, you can use either a list of lines or loop through each line you want to add and write them one by one.

Q4. What’s the best way to handle files safely?

The best way to handle a file safely is to use the with statement when working with files. It ensures the file is automatically closed after use.

Q5. How can I avoid accidentally deleting existing file content?

Use append mode instead of write mode if you want to keep the existing content and just add more data.

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

EPGC Data Science Artificial Intelligence