Table of contents
1.
Introduction 
2.
File Access Modes
3.
How Files are Loaded into Primary Memory?
4.
Opening a Text File in Python
5.
Closing a Text File in Python
6.
Writing to a File in Python
6.1.
Using write()
7.
Using writelines()
8.
Reading from a File in Python
8.1.
Using read()
8.2.
Using readline()
8.3.
Using readlines()
9.
Appending to a File in Python
10.
Frequently Asked Questions
10.1.
What happens if I try to read from a file that doesn't exist?
10.2.
Can I read & write to the same file simultaneously?
10.3.
Is it necessary to close a file after reading from or writing to it?
11.
Conclusion
Last Updated: Aug 8, 2024
Easy

How to Read Text File in Python

Author Rahul Singh
0 upvote

Introduction 

In Python, every programmer should know how to work with files. It’s an essential skill, wheather you're reading data from a file, writing output to a file, or manipulating file contents, understanding how to handle files is crucial. 

How to Read Text File in Python

In this article, we'll talk about the basics of reading text files in Python. We'll also discuss how to open files, read their contents, close them properly, & discuss various methods to read data efficiently. 

File Access Modes

Before we talk about reading files, let's first understand the different file access modes available in Python. When opening a file, you need to specify the mode in which you want to open it. The most commonly used modes are:

1. "r" (Read Mode): This is the default mode. It allows you to read the contents of a file. If the file doesn't exist, an error will occur.
 

2. "w" (Write Mode): This mode allows you to write to a file. If the file already exists, its contents will be overwritten. If the file doesn't exist, a new file will be created.
 

3. "a" (Append Mode): This mode allows you to append content to the end of a file. If the file doesn't exist, a new file will be created.
 

4. "x" (Exclusive Creation Mode): This mode is used to create a new file exclusively. If the file already exists, an error will be raised.
 

5. "t" (Text Mode): This is the default mode for text files. It specifies that the file should be handled as text.
 

6. "b" (Binary Mode): This mode is used when working with binary files, such as images or executable files.


You can combine these modes to perform specific operations. For example, "rt" means open the file in read mode as a text file, while "wb" means open the file in write mode as a binary file.

How Files are Loaded into Primary Memory?

When you open a file in Python, it is loaded into the primary memory (RAM) of your computer. This allows faster access to the file's contents compared to reading directly from the hard disk. Here's how the process works:

1. File Opening: When you use the `open()` function to open a file, Python locates the file on the hard disk & creates a file object in memory. This file object serves as a reference to the actual file on the disk.
 

2. File Pointer: Python maintains a file pointer that keeps track of the current position within the file. Initially, the file pointer is positioned at the beginning of the file.
 

3. Reading Data: As you read data from the file using methods like `read()`, `readline()`, or `readlines()`, Python moves the file pointer accordingly & retrieves the requested data from the file. The data is transferred from the hard disk to the primary memory for faster access.
 

4. Memory Buffer: Python uses a memory buffer to store the data read from the file. This buffer allows efficient reading & manipulation of the file's contents without constantly accessing the hard disk.
 

5. File Closing: When you're done working with the file, it's important to close it using the `close()` method. Closing the file releases the memory buffer & any system resources associated with the file object.


It's important to remember that when working with large files, it's more memory-efficient to read the file in smaller chunks rather than loading the entire file into memory at once. Python provides various methods to read files in a memory-friendly manner, which we'll explore in the upcoming sections.

Opening a Text File in Python

To start reading from a text file, you first need to open it. In Python, you can use the built-in `open()` function to open a file. 

Let’s see the syntax : 

file_object = open("file_path", "access_mode")


- `"file_path"`: This is a string that represents the path to the file you want to open. It can be an absolute path or a relative path from your Python script's location.

- `"access_mode"`: This is a string that specifies the mode in which you want to open the file. As discussed earlier, the most common mode for reading a text file is "r".


Let’s see an example of opening a text file named "example.txt" in read mode:

file = open("example.txt", "r")


If the file is located in the same directory as your Python script, you can simply provide the file name. If the file is in a different location, you'll need to specify the appropriate path.

Once you have opened the file, you can perform various operations on it, such as reading its contents, which we'll cover in the next sections.

Note: It's important to remember that you should always close the file when you're done working with it to free up system resources. 

Closing a Text File in Python

After you've finished working with a file, it's crucial to close it properly. Closing a file ensures that any changes you made are saved & releases the system resources associated with the file. In Python, you can close a file using the `close()` method. 

For example:

file = open("example.txt", "r")
# Perform file operations
file.close()


It's a good practice to close the file as soon as you're done with it to avoid unnecessarily holding up system resources. However, there's a more convenient & safer way to handle file closing using the `with` statement. The `with` statement automatically takes care of closing the file for you, even if an exception occurs during file operations. 

For example 

with open("example.txt", "r") as file:
    # Perform file operations


In this case, you don't need to explicitly call the `close()` method. The file will be automatically closed once the block inside the `with` statement is executed, regardless of any exceptions that may occur.

Writing to a File in Python

Now that you know how to open & close files, let's explore how to write data to a file using Python. There are two main methods for writing to a file: `write()` & `writelines()`. 

Let’s discuss both the methods in detail : 

Using write()

The `write()` method is used to write a string of data to a file. 


For example 

with open("example.txt", "w") as file:
    file.write("Hello, World!")


In this code , we open the file "example.txt" in write mode using the `with` statement. Then, we use the `write()` method to write the string "Hello, World!" to the file. If the file already exists, its contents will be overwritten. If the file doesn't exist, a new file will be created.

You can also write multiple lines to a file by calling the `write()` method multiple times:

with open("example.txt", "w") as file:
    file.write("Line 1\n")
    file.write("Line 2\n")
    file.write("Line 3\n")


In this example, we write three lines to the file, each ending with a newline character (`\n`) to start a new line.

Using writelines()

The `writelines()` method is used to write a list of strings to a file. Each string in the list represents a line in the file. 

For example :

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)


In this code, we have a list called `lines` that contains three strings, each representing a line. We open the file "example.txt" in write mode & use the `writelines()` method to write the entire list of strings to the file. Each string in the list will be written as a separate line in the file.

It's important to note that when using `writelines()`, you need to include the newline characters (`\n`) in the strings if you want each string to be written on a new line.

Note: Both `write()` & `writelines()` methods are useful for writing data to files in Python. We can identify the best method on the basis of whether you have a single string or a list of strings to write.

Reading from a File in Python

Reading data from a file is a common task in Python programming. Python provides several methods to read the contents of a file. Let's explore the most commonly used methods: `read()`, `readline()`, & `readlines()`.

Using read()

The `read()` method is used to read the entire contents of a file as a single string. 

For example:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)


In this code, we open the file "example.txt" in read mode using the `with` statement. Then, we use the `read()` method to read the entire contents of the file & store it in the variable `content`. Finally, we print the contents of the file.

You can also specify the number of characters to read by passing an argument to the `read()` method:

with open("example.txt", "r") as file:
    content = file.read(10)
    print(content)


In this case, the `read()` method will read the first 10 characters from the file.

Using readline()

The `readline()` method is used to read a single line from the file. It reads characters from the current position until it reaches a newline character (`\n`) or the end of the file. 

For example:

with open("example.txt", "r") as file:
    line = file.readline()
    print(line)


In this code, we use the `readline()` method to read the first line of the file & store it in the variable `line`. We then print the line.

You can call `readline()` multiple times to read subsequent lines:

with open("example.txt", "r") as file:
    line1 = file.readline()
    line2 = file.readline()
    print(line1)
    print(line2)


Each call to `readline()` moves the file pointer to the next line, allowing you to read the file line by line.

Using readlines()

The `readlines()` method is used to read all the lines of a file & return them as a list of strings. Each string in the list represents a line from the file. 

For example:

with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line)


In this code, we use the `readlines()` method to read all the lines of the file & store them in the `lines` list. We then iterate over each line in the list using a `for` loop & print each line.

The `readlines()` method is useful when you want to process each line of the file separately or store them in a list for further manipulation.

Appending to a File in Python

In addition to writing & reading files, Python allows you to append data to an existing file without overwriting its contents. Appending is useful when you want to add new data to the end of a file while preserving the existing data. Let's see how you can append to a file in Python.

To append data to a file, you need to open the file in append mode by passing the "a" access mode to the `open()` function. 

For example

with open("example.txt", "a") as file:
    file.write("This is a new line appended to the file.\n")


In this code, we open the file "example.txt" in append mode using the `with` statement. Then, we use the `write()` method to append a new line to the end of the file. The new line will be added after the existing content of the file.

You can append multiple lines to a file by calling the `write()` method multiple times or by using the `writelines()` method with a list of strings:

lines = ["Line 4\n", "Line 5\n", "Line 6\n"]
with open("example.txt", "a") as file:
    file.write("This is a new line appended to the file.\n")
    file.writelines(lines)


In this example, we first append a single line using the `write()` method. Then, we use the `writelines()` method to append a list of strings (`lines`) to the file. Each string in the list represents a new line that will be appended to the file.

When you open a file in append mode, the file pointer is positioned at the end of the file. This means that any new data you write will be appended after the existing content without overwriting it.

Frequently Asked Questions

What happens if I try to read from a file that doesn't exist?

If you try to open a file that doesn't exist in read mode, Python will raise a FileNotFoundError exception.

Can I read & write to the same file simultaneously?

Yes, you can open a file in both read & write modes by using the "r+" access mode. However, be cautious when doing this to avoid unintended modifications to the file.

Is it necessary to close a file after reading from or writing to it?

Yes, it's important to close a file after you're done with it to release system resources. Using the with statement ensures that the file is automatically closed, even if an exception occurs.

Conclusion

In this article, we have learned the basics of reading text files in Python. We discussed how to open files in different access modes, read their contents using methods like read(), readline(), & readlines(), & properly close files. We also explained writing to files using the write() & writelines() methods & appending to files.

You can also check out our other blogs on Code360.

Live masterclass