File Handling

File handling in Python allows you to work with files – creating, reading, writing, and closing them. It is an essential feature for tasks like storing data, processing text files, or generating reports.

Opening a File

To work with a file, you first need to open it using the open() function. The syntax is:

Python
Copy
file = open(filename, mode)
  • filename: The name of the file (e.g., "data.txt").
  • mode: Specifies what you want to do with the file.

File Modes

Mode Description
"r" Read mode (default). Opens a file for reading.
"w" Write mode. Creates a new file or overwrites an existing file.
"a" Append mode. Adds data to the end of an existing file.
"x" Create mode. Creates a file; raises an error if the file exists.
"t" Text mode (default). Reads/writes text.
"b" Binary mode. Reads/writes binary data.

Reading a File

You can read the contents of a file using various methods:

  1. read(): Reads the entire file.
  2. readline(): Reads one line at a time.
  3. readlines(): Reads all lines and returns them as a list.

Examples:

Python
Copy
# Example file: "example.txt" contains "Hello\nWorld"

# Open the file in read mode
file = open("example.txt", "r")

# Read the entire content
content = file.read()
print(content)  # Output: Hello\nWorld

# Close the file
file.close()

Writing to a File

To write data into a file, open it in "w" (write) or "a" (append) mode.

  1. write(): Writes a string to the file.
  2. writelines(): Writes a list of strings to the file.

Examples:

Python
Copy
# Open a file in write mode
file = open("example.txt", "w")

# Write data
file.write("Hello World")
file.close()

Python
Copy
# Append data to the file
file = open("example.txt", "a")
file.write("\nAppended Text")
file.close()

Closing a File

Always close a file after you are done with it to free system resources. Use the close() method.

Example:

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

Using with Statement

Using with ensures the file is automatically closed after you are done with it.

Example:

Python
Copy
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed after this block

Checking if a File Exists

Use the os module to check if a file exists.

Example:

Python
Copy
import os

if os.path.exists("example.txt"):
    print("File exists!")
else:
    print("File does not exist.")

Working with Text and Binary Files

  1. Text Files: Use "t" mode (default). Handles strings.
  2. Binary Files: Use "b" mode. Handles binary data like images.

Example (Binary Mode):

Python
Copy
# Copy a binary file (e.g., an image)
with open("image.jpg", "rb") as source:
    with open("copy.jpg", "wb") as destination:
        destination.write(source.read())

Deleting a File

To delete a file, use the os module's remove() method.

Example:

Python
Copy
import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted.")
else:
    print("File not found.")

Handling Exceptions

When working with files, it's a good practice to handle exceptions to avoid runtime errors.

Example:

Python
Copy
try:
    file = open("example.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("File not found!")
finally:
    if file:
        file.close()