Introduction:

In Python, files allow us to store and read data that persists even after a program finishes running. This is essential for many tasks, such as saving user data, reading configurations, or processing large datasets. Python provides several ways to work with files, and understanding how to open, read, and close files is a fundamental programming skill.

Opening and Closing Files

The open() function in Python is used to open files. When you open a file, you can specify the mode in which you want to operate on the file:

  • r: Read mode (default) – opens the file for reading. If the file doesn’t exist, an error is raised.
  • w: Write mode – opens the file for writing, overwriting the file if it exists or creating a new one if it doesn’t.
  • a: Append mode – opens the file for appending data to the end of the file.
  • r+: Read/Write mode – allows both reading and writing to the file.

After opening the file, it’s important to close it using close() to free up system resources. However, a more efficient and safer way to handle files is by using the with open() context manager. This automatically handles the closing of the file, even if an error occurs while working with the file.

Retrieving Data from Files

Once a file is opened in read mode, you can retrieve its content in several ways:

  • read(): Reads the entire content of the file as a single string.
  • readline(): Reads the file one line at a time.
  • readlines(): Reads all the lines of a file and returns them as a list.

Let’s look at a few examples of how this works in practice.

Example 1: Reading the Entire File Using read()

The read() method reads the entire content of a file at once and returns it as a string.

In this example, the file example.txt contains multiple lines. When you use file.read(), it reads everything from the file and stores it in the content variable, which is then printed. The file is automatically closed after reading.

Example 2: Reading Line by Line Using readline()

The readline() method allows us to read one line at a time from a file. This is useful when you want to process a file line by line.

In this example, readline() is called twice to read and print the first two lines of the file. Each time it's called, it reads the next line in the file.

Example 3: Reading All Lines Using readlines()

The readlines() method reads all the lines of a file and returns them as a list, where each element of the list is a line from the file.

In this example, readlines() reads all the lines and stores them as a list, where each element represents a line in the file. This is useful when you need to work with all the lines as separate items, such as processing a list of students or items.

Closing Files

While using open() without the with statement requires us to manually close the file with file.close(), using with open() ensures the file is closed automatically when the block of code is finished. This is the safer and preferred method for file handling in Python.

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

This code works, but if an error occurs before file.close() is called, the file might remain open, which is why with open() is recommended.

Conclusion:

Files allow you to store, read, and process data outside of your program, making it possible to work with large datasets, configurations, and logs. By using methods like read(), readline(), and readlines(), you can retrieve data in various ways to suit your needs. Using with open() ensures that files are handled safely and automatically closed after use.

This knowledge is vital in many real-world applications, such as processing user data, managing configurations, or analysing large files.

Predict:

Take a look at the following code. What do you think it will print?

# Opening a file and reading its content
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()

In this example, the program opens a file named "data.txt" in read mode ("r") and reads its content. What do you think will be printed if the file contains the following text:

Hello, this is a test file.
This is the second line.

Run:

Let’s try a simple example where we open a file, read its contents, and then close the file using Python’s file handling methods.

Here, we use the with open() method, which is preferred because it automatically closes the file after reading. Try running this code and observe how the file’s content is printed.

Investigate:

Now let’s explore reading files line by line using readline(). This can be useful if you only need to process part of a file or handle very large files where reading the whole file at once isn't practical.

Run the code and observe how each line is read separately. Think about when this might be useful for processing large files, like logs.

Modify:

Let’s modify this code. Below is a program that reads a file but doesn’t print all the lines. Can you fix it so that it reads all lines and prints each one?

Hint: Use a loop to iterate over the lines in the file and print each one.

Scroll to Top