Python File Handling: A Complete Tutorial for Beginners

Last updated 5 months, 1 week ago | 365 views 75     5

Tags:- Python

File handling is a crucial skill for any Python programmer. It allows you to read from and write to files, automate workflows, process logs, store user data, and much more. Python provides simple yet powerful ways to interact with files using built-in functions like open(), read(), write(), and close().

In this tutorial, you’ll learn:

  • What file handling is

  • How to open, read, write, and close files

  • File modes in Python (r, w, a, etc.)

  • Using the with statement

  • Handling text and binary files

  • Tips and common pitfalls


What Is File Handling?

File handling means working with files — creating, opening, reading, writing, appending, and closing them. In Python, this is typically done using the built-in open() function and file object methods.


Opening a File

The open() function is used to open a file:

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

Syntax:

open(file, mode='r', buffering=-1, encoding=None, errors=None)

Common File Modes:

Mode Description
'r' Read (default). File must exist.
'w' Write. Overwrites file or creates a new one.
'a' Append. Adds to the end of file.
'x' Exclusive creation. Fails if file exists.
'b' Binary mode (e.g., 'rb', 'wb')
't' Text mode (default)

Reading from a File

.read(): Read entire content

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

.readline(): Read line-by-line

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

.readlines(): Read all lines as a list

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

✍️ Writing to a File

.write(): Write string to file

with open("output.txt", "w") as file:
    file.write("Hello, Python!\n")
    file.write("File handling is easy.")

⚠️ w mode will overwrite the file if it already exists.

.writelines(): Write a list of strings

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

➕ Appending to a File

To add content to an existing file without deleting its contents, use 'a' mode:

with open("output.txt", "a") as file:
    file.write("New appended line.\n")

✅ Using the with Statement (Best Practice)

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

Benefits of with:

  • Automatically closes the file

  • Prevents file corruption

  • Cleaner and safer


Working with Binary Files

To handle binary files like images or videos:

Reading binary file:

with open("image.png", "rb") as file:
    content = file.read()

Writing binary file:

with open("copy.png", "wb") as file:
    file.write(content)

Handling File Exceptions

try:
    with open("important.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File does not exist.")
except IOError:
    print("An I/O error occurred.")

Complete Example: Copying Text from One File to Another

def copy_file(source, destination):
    try:
        with open(source, "r") as src, open(destination, "w") as dest:
            for line in src:
                dest.write(line)
        print("File copied successfully.")
    except FileNotFoundError:
        print("Source file not found.")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
copy_file("input.txt", "output.txt")

⚠️ Common Pitfalls and How to Avoid Them

Pitfall Solution
Forgetting to close files Use with open(...)
File not found Use try-except or check with os.path.exists()
Using wrong mode (r when file doesn’t exist) Use w, a, or check before opening
Writing without newline Use \n at the end of each line

Tips for Effective File Handling

  • Always use with to manage file context

  • For large files, process line-by-line instead of using .read()

  • Use 'b' mode for binary files (e.g., images, PDFs)

  • Handle exceptions to avoid crashing your program

  • Use os.path.exists() or pathlib.Path.exists() to verify files


Summary Table

Task Method
Open a file open("file.txt", "r")
Read file .read(), .readline(), .readlines()
Write to file .write(), .writelines()
Append to file open("file.txt", "a")
Read/write binary Use 'rb' / 'wb' modes
Best practice with open(...) as file:

Final Thoughts

Python file handling is simple, readable, and powerful. Whether you're dealing with logs, user data, configuration files, or large datasets, understanding how to work with files effectively is an essential skill. Always follow best practices, handle exceptions gracefully, and ensure data integrity by properly closing files.