Skip to content
Home » File Handling in Python: A Complete Guide for Beginners

File Handling in Python: A Complete Guide for Beginners

  • by

Working with files is an essential skill in any programming language — and Python makes file handling simple, readable, and powerful. Whether you’re saving user input, reading configuration files, or logging app data, this guide will help you master file handling in Python from scratch.


What Is File Handling?

File handling allows your Python program to:

  • Create files
  • Read content from files
  • Write data to files
  • Modify existing content
  • Delete files

Python uses built-in functions and a simple syntax to interact with text or binary files.


Opening a File in Python

Use the built-in open() function:

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

Syntax:

pythonCopyEditopen(filename, mode)

Common File Modes:

ModeDescription
"r"Read (default mode)
"w"Write (overwrites file)
"a"Append (adds to file)
"x"Create (fails if file exists)
"b"Binary mode
"t"Text mode (default)

You can combine modes like "rb" or "wt".


Reading a File in Python

Assume example.txt contains:

Hello
Welcome to Python

Method 1: read()

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

Method 2: readline() (reads one line)

file = open("example.txt", "r")
line1 = file.readline()
line2 = file.readline()
print(line1, line2)
file.close()

Method 3: readlines() (returns list)

file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
print(line.strip())
file.close()

Writing to a File

Overwrite a File

file = open("example.txt", "w")
file.write("This replaces everything.\n")
file.write("Second line.")
file.close()

Append to a File

file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()

Using with Statement (Best Practice)

Using with ensures that the file is closed automatically, even if an error occurs:

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

No need to call file.close() manually.


Writing and Reading Simultaneously

Use mode "r+" (read + write):

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

Working with Binary Files

For images, PDFs, etc.:

with open("image.jpg", "rb") as file:
data = file.read()

Checking if a File Exists

Use the os module:

import os

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

Deleting a File

import os

os.remove("example.txt")

File Handling Example: Copy Content

with open("source.txt", "r") as src:
with open("destination.txt", "w") as dest:
dest.write(src.read())

Common File Handling Errors

ErrorReasonFix
FileNotFoundErrorFile doesn’t existCheck filename/path
PermissionErrorNo write accessRun with proper permissions
IOErrorGeneral file I/O problemUse try...except to handle it

Example:

try:
with open("data.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found.")

Final Tips

Always use with open() for safe file operations
Don’t forget to handle errors with try-except blocks
Use relative paths when working across multiple systems
Avoid hardcoding filenames if possible


Conclusion

Python’s file handling is one of its many beginner-friendly features. With just a few lines of code, you can read, write, and manage files — whether it’s logs, data sets, or reports.

Once you’re comfortable with basic file I/O, explore more advanced topics like:

  • Working with CSV and JSON files
  • Reading large files efficiently
  • Handling directories and file trees

Leave a Reply

Your email address will not be published. Required fields are marked *