File Handling in Python

What is File Handling? File handling means working with files to save or read data. In Python, you can open files, write to them, read from them, and close them easily. It is useful for storing and managing information, like saving a list of names or reading a saved report.

1. Opening a File

Before we can work with a file (like reading its content or writing something into it), we must open it. Python provides an easy way to do this using the open() function.

The open() function needs two things:

  1. The name of the file you want to work with.
  2. The mode, which tells Python how you want to open the file.

Common Modes in open():

Example 1: Open a File in Read Mode

Let’s say we have a file named example.txt that contains some text. We want to open it and read its content:

# Example: Open and Read a File
file = open("example.txt", "r")  # Open the file in 'r' (read) mode
content = file.read()  # Read the entire content of the file
print(content)  # Display the content on the screen
file.close()  # Close the file after use
  

Output:

If example.txt contains:

Hello, this is a sample file.
Welcome to Python file handling!

The program will display:

Hello, this is a sample file.
Welcome to Python file handling!

Step-by-Step Explanation:

  1. file = open("example.txt", "r"): This opens the file named example.txt in read mode ('r'). If the file doesn’t exist, Python will show an error.
  2. content = file.read(): The read() method reads all the text inside the file and stores it in the variable content.
  3. print(content): This displays the file’s content on the screen.
  4. file.close(): After finishing, always close the file using close(). This frees up resources and prevents errors.

Important Notes:

Example 2: What Happens if the File Doesn’t Exist?

Let’s try to open a file that does not exist:

# Trying to open a non-existent file
file = open("nonexistent.txt", "r")  # This file does not exist
content = file.read()
print(content)
file.close()
  

This will give an error:

FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'

How to Handle Such Errors:

We can avoid this error by using a try and except block:

# Handle error if file doesn't exist
try:
    file = open("nonexistent.txt", "r")  # Trying to open a non-existent file
    content = file.read()
    print(content)
    file.close()
except FileNotFoundError:
    print("The file does not exist. Please check the file name.")
  

Output:

Instead of crashing, the program will display:

The file does not exist. Please check the file name.

Example 3: Use the with Statement

A better way to open files is by using the with statement. This ensures the file is automatically closed after its use:

# Using 'with' to open a file
with open("example.txt", "r") as file:
    content = file.read()  # Read the file
    print(content)  # Print the content
# No need to call file.close(); it’s done automatically
  

Using with is safer and more efficient because Python handles closing the file for you.

2. Reading from a File

Python provides multiple ways to read data:

Example: Read File Line by Line

# Read a file line by line
file = open("example.txt", "r")
for line in file:  # Loop through each line
    print(line.strip())  # Print each line without extra spaces
file.close()
    

Explanation: The for loop goes through each line in the file. strip() removes unnecessary spaces.

3. Writing to a File

To write new data to a file, we use the write() method. However, be careful when using 'w' mode, because it will erase everything already in the file and replace it with the new content you write.

Example 1: Write to a File

Let’s say we want to create a file or overwrite an existing file, and then write some new content into it. Here’s how you do it:

# Example: Write new data to a file
file = open("example.txt", "w")  # 'w' mode opens the file for writing (it overwrites the file if it exists)
file.write("Hello, Python learners!\n")  # Write a line of text
file.write("File handling is easy to learn.")  # Write another line of text
file.close()  # Always close the file when done
  

Output in the file:

Hello, Python learners!
File handling is easy to learn.

Explanation:

Important Points about Writing:

4. Appending to a File

If you want to add new data to the end of an existing file without removing the current content, you can use 'a' mode. This is called appending.

Example 2: Append to a File

Now, let’s say we want to add some more content to example.txt without losing the existing text. Here's how you do it:

# Example: Add more data to an existing file
file = open("example.txt", "a")  # 'a' mode opens the file for appending (doesn't erase existing content)
file.write("\nThis line is added to the file.")  # Append a new line of text
file.close()  # Always close the file when done
  

Output in the file:

Hello, Python learners!
File handling is easy to learn.
This line is added to the file.

Explanation:

Important Points about Appending:

Summary:

- Use 'w' mode to overwrite a file and write new content. Be careful, as it will erase any previous data in the file.

- Use 'a' mode if you want to add new content to an existing file without removing anything.

5. Handling Errors

What if the file doesn’t exist? Or you don’t have permission to open it? Python allows you to handle such errors using try and except.

Example: Handle Missing File Error

# Handle file errors
try:
    file = open("missing_file.txt", "r")  # This file doesn't exist
    print(file.read())
    file.close()
except FileNotFoundError:
    print("The file does not exist. Please check the filename.")
    

Explanation: The try block attempts to open a file. If the file is not found, the except block runs, displaying an error message.

6. Closing a File

Always close a file after using it with the close() method. This frees up system resources.

Better Way to Work with Files

Use the with statement to automatically close files:

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

Explanation: The with block automatically closes the file when done. It’s safer and easier to use.

Summary of Key Points: