Python File Handling

August 06, 2025   5 Min Read 30

What You’ll Learn in This Blog

  • What is file handling in Python?
  • Opening a file (modes: read, write, append)
  • Reading from files (read(), readline(), readlines())
  • Writing and appending to files
  • Using with statement for clean file handling
  • Working with file paths
  • Best practices and common mistakes

What is File Handling?

File handling allows your Python program to interact with files on your computer: reading data from files or writing data to them.

Python provides built-in functions to work with files using:


open(filename, mode)

File Modes in Python

ModeDescription
'r'Read (default) – Error if file doesn't exist
'w'Write – Creates file or overwrites if it exists
'a'Append – Creates file or appends if it exists
'x'Create – Creates new file; fails if file exists
'b'Binary mode (e.g., 'rb', 'wb')
't'Text mode (default)

Opening a File


file = open("data.txt", "r")  # Opens in read mode

Always close a file when you;re done:


file.close()

But instead of manually opening and closing, it's better to use with statement (explained below).

Reading from a File

Method 1: read(): Reads the entire file


with open("data.txt", "r") as f:
	content = f.read()
	print(content)

Method 2: readline(): Reads one line at a time


with open("data.txt", "r") as f:
	line1 = f.readline()
	line2 = f.readline()
	print(line1, line2)

Method 3: readlines(): Reads all lines into a list


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

Writing to a File

'w' mode overwrites the file:


with open("data.txt", "w") as f:
	f.write("Hello, Akash!\n")
	f.write("Welcome to Python file handling tutorial.")

Appending to a File

'a' mode adds content to the end:


with open("data.txt", "a") as f:
	f.write("\nThis is an additional line.")

Using with Statement (Context Manager)

The with statement automatically close the file even if an error occurs.


with open("data.txt", "r") as f:
	data = f.read()
	print(data)
# File is now close automatically

Why use with?

  • Avoids forgetting file.close()
  • Cleaner and safer code

Handling File Paths

To avoid errors across platforms, use os.path:


import os

path = os.path.join("folder", "data.txt")
with open(path, "r") as f:
	print(f.read())

or use absolute paths carefully:


with open("/home/akash/documents/data.txt") as f:
	...

Common Mistakes to Avoid

  • Not closing the file manually (if not using with)
  • Using 'w' instead of 'a' when you want to append
  • Reading a file that doesn't exist (check with os.path.exists() if needed)

Practice Task

🔸 Create  text file named log.txt. Write a Python script that:

  1. Appends the current timestamp and a message to the file each tiime it's run.
  2. Then reads and prints the entire content of log.txt.

💡 Hint: Use datetime.now() from the datetime module.

Summary

OperationMethod/Example
Read entireread()
Read one linereadline()
Read all linesreadlines()
Write filewrite() in 'w' mode
Append filewrite() in 'a' mode
Safe handlingwith open(...) as f:
Pathsos.path.join() for safe paths

Leave a Reply