Mastering File Handling in Python

Introduction

File handling is a crucial aspect of programming that allows you to read and write data to and from files on their computers. Python, being a powerful and versatile programming language, has excellent support for file handling. In this article, we will explore the various file handling operations that Python offers.

Opening a File

Before you can perform any file handling operations in Python, you need to open the file first. One way to achieve this is by utilizing the `open()` function, which requires two parameters: the desired file name and the preferred file opening mode.

Here’s the basic syntax for opening a file:


file = open("filename.txt", "mode")

In this syntax, “filename.txt” is the name of the file you want to open, and “mode” is the mode in which you want to open the file.

Here’s an example of how to open a file in read mode:


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

In this example, we are opening a file named “filename.txt” in read mode. Once you have opened a file, you can perform various operations on it, such as reading its contents or writing to it.

After you are done with the file, it is important to close it using the close() method. This ensures that any changes you made to the file are saved and that system resources are freed up.

Here’s an example of how to open a file in read mode, read its contents, and then close it:


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

In this example, we are opening a file named “filename.txt” in read mode, reading its contents using the read() method, printing the contents to the console, and then closing the file using the close() method.

An alternative method for opening a file in Python involves utilizing the `with` statement. The `with` statement provides a context in which the file is opened, and once the context is exited, the file is automatically closed. This ensures that the file is properly closed even if an error occurs during the operation.

Here’s the basic syntax for opening a file using the `with` statement:


with open("filename.txt", "mode") as file:
    # perform file operations here

In this syntax, “filename.txt” is the name of the file you want to open, “mode” is the mode in which you want to open the file, and file is a variable that refers to the `file` object.

Here’s an example of how to open a file using the `with` statement, read its contents, and then print them to the console:


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

In this example, we are opening a file named “filename.txt” in read mode using the `with` statement. Inside the `with` block, we are reading the contents of the file using the `read()` method and storing it in the `content` variable. We are then printing the contents of the file to the console. Once the `with` block is exited, the file is automatically closed.

Type of Modes Used to Open a File

Mode Description
‘r’ Read Mode: This is the default mode for opening a file. It allows you to read the contents of a file. If the file does not exist, it will raise an error.
‘w’ Write Mode: This mode allows you to write to a file. If the file already exists, its contents will be overwritten. If it doesn’t exist, a new file will be created.
‘a’ Append Mode: This mode allows you to append data to the end of a file. If the file doesn’t exist, a new file will be created.
‘x’ Exclusive Creation Mode: This mode creates a new file, but it will fail if the file already exists.
‘b’ Binary Mode: This mode is used to read or write binary data, such as images or sound files.
‘t’ Text Mode: This mode is used to read or write text files. This is the default mode if “b” is not included.
‘+’ Updating Mode: This mode allows you to read and write to a file. If the file doesn’t exist, it will raise an error.
‘rb’ Reading in binary mode
‘r+’ To read and write both
‘rb+’ Reading and writing in binary
‘w+’ Write and Read both
‘wb’ Write in binary mode
‘a+’ Append and read both (In this case, file pointer points to the end of the file)
‘ab’ Append in binary mode
‘ab+’ Append and read in binary mode

Reading From a File

In Python, there are several ways to read the contents of a file. Here are the most commonly used methods for reading a file:

1. `read()`: This method reads the entire contents of a file and returns it as a single string. Here’s an example:


with open("file.txt", "r") as f:
    contents = f.read()
    print(contents)

2. `readline()`: This method reads one line of a file at a time and returns it as a string. Here’s an example:


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

In this example, we are reading one line of the file at a time using a `while` loop.

3. `readlines()`: This method reads all the lines of a file and returns them as a list of strings. Here’s an example:


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

In this example, we are reading all the lines of the file at once using the `readlines()` method and iterating over the list of lines using a `for` loop.

Imagine that you want to print only the initial two lines of a file rather than the remaining content. To achieve this objective, you may utilize the `readlines()` method and a list technique in Python. Here’s an example:


with open('file.txt', 'r') as f:
    # It will iterate through the first two lines.
    for line in f.readlines()[:2]:
        print(line, end='')

In this instance, we employed the list slicing technique (as seen in the yellow line) and therefore the loop traverses through the first two lines of the given file.

It’s important to note that when reading a file, the file pointer moves as data is read from the file. To reset the file pointer to the beginning of the file, you can use the `seek()` method. Here’s an example:


with open("file.txt", "r") as f:
    # read some data from the file
    data = f.read(10)
    print(data)

    # reset the file pointer to the beginning of the file
    f.seek(0)

    # read the entire file
    contents = f.read()
    print(contents)

In this example, we are reading 10 characters from the file using the `read()` method and then resetting the file pointer to the beginning of the file using the `seek()` method. We are then reading the entire contents of the file using the `read()` method again.

Writing to a File

There are several ways to write to a file. Here are the most commonly used methods for writing to a file:

1. `write()`: This method writes a string to a file. If the file does not exist, it will be created. In case it already exists, the file’s contents will be overwritten. Here’s an example:


with open("file.txt", "w") as f:
    f.write("Hello, world!")

In this example, we are writing the string “Hello, world!” to a file called “file.txt” using the `write()` method.

2. `writelines()`: This method writes a list of strings to a file. If the file does not exist, it will be created. In case it already exists, the file’s contents will be overwritten. Here’s an example:


with open("file.txt", "w") as f:
    lines = ["Hello", "world", "from", "Python!"]
    f.writelines(lines)

In this example, we are writing a list of strings to a file called “file.txt” using the `writelines()` method.

3. `print()`: You can also write to a file using the `print()` function by specifying the file parameter. Here’s an example:


with open("file.txt", "w") as f:
    print("Hello, world!", file=f)

In this example, we are using the `print()` function to write the string “Hello, world!” to a file called “file.txt” by specifying the `file` parameter.

It’s important to note that when writing to a file, you should make sure to close the file using the `close()` method to ensure that any changes you made are saved and that system resources are freed up. Here’s an example:


f = open("file.txt", "w")
f.write("Hello, world!")
f.close()

In this example, we are opening a file called “file.txt” in write mode using the `open()` function, writing the string “Hello, world!” to the file using the `write()` method, and then closing the file using the `close()` method.

Appending to a File

To append data to an existing file in Python, you can open the file in append mode using the “a” parameter in the `open()` function. Here’s an example:


with open("file.txt", "a") as f:
    f.write("This text will be appended to the file")

In this example, we are opening the file “file.txt” in append mode by specifying “a” as the second parameter in the `open()` function. Then, we write the string “This text will be appended to the file” to the file using the `write()` method.

It’s important to note that when you open a file in append mode, any data you write to the file will be added to the end of the existing data in the file. If the file does not exist, it will be created. If it already exists, the data you append will be added to the end of the file without overwriting any of the existing data.

It’s also important to remember to close the file using the `close()` method or using the `with` statement to ensure that any changes you made are saved and that system resources are freed up.

The seek() function

The `seek()` function in Python is used to change the current position (or offset) of the file pointer within a file. It allows you to move the file pointer to a specific location within the file, which enables you to perform various operations such as reading, writing, or appending data at a specific position.

The syntax of the `seek()` function is as follows:


file.seek(offset, whence)

Here, `file` is the file object, `offset` is the number of bytes to move the file pointer, and `whence` specifies the reference position for the offset. The `whence` parameter is optional and its default value is `0`, which means the offset is relative to the beginning of the file.

The `whence` parameter can take the following values:

  • `0` (default): The offset is relative to the beginning of the file.
  • `1`: The offset is relative to the current position of the file pointer.
  • `2`: The offset is relative to the end of the file.

By using the `seek()` function, you can perform actions such as reading a specific portion of a file or updating data at a specific position. For example, to read only a portion of a file, you can set the file pointer to the desired position using `seek()` and then use the appropriate reading method.

Here’s an example that demonstrates the usage of `seek()`:


with open("file.txt", "r") as file:
    file.seek(10)  # Move the file pointer to the 10th byte
    data = file.read()  # Read from the 10th byte onwards
    print(data)

In this example, the file pointer is moved to the 10th byte using `seek(10)`, and then the `read()` method is used to read the contents from that position onward.

Exercises

Here are a few exercises to practice file handling in Python:

  1. Write a program that prompts the user to enter their name and saves it to a file called “names.txt”.
  2. Create a file called “numbers.txt” and write the numbers 1 to 10, each on a new line.
  3. Write a program that reads the contents of a file called “data.txt” and calculates the average of the numbers in the file.
  4. Write a program that reads a text file called “poem.txt” and counts the number of words in it. Display the total word count to the user.
  5. Create a file called “shopping_list.txt” and allow the user to add items to the list. Each time the user adds an item, it should be appended to the file on a new line.
  6. Write a program that reads a CSV file called “data.csv” (comma-separated values) and prints the data in a tabular format.
  7. Create a file called “log.txt” and write a program that asks the user to enter a log entry. Each log entry should be timestamped and appended to the file.
  8. Write a program that reads a file called “inventory.txt” containing a list of items and their quantities. Allow the user to search for an item and display its quantity.
  9. Create a program that renames a file. Prompt the user to enter the current filename and the new filename, and rename the file accordingly.
  10. Write a program that reads a file called “scores.txt” containing a list of student scores. Calculate the average score and determine the highest and lowest scores in the file.

These exercises should provide a good starting point for practicing file handling in Python. You can modify them or add more complexity to further enhance your skills.

Important Note: Remember to always close your files after you are done with them or use the `with` statement to avoid any potential issues.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 147