Saturday , December 5 2026
Python File Handling - Opening and Closing Files, Reading and Writing files

Python Files Handling

Updated: 28 November 2026Level: BeginnerReading time: about 10 minutesPython 3.8+

File handling lets your program save data permanently and read it back later. You will use it to load datasets, write logs, save results and read configuration files.

What You Will Learn

  • Opening files with modes
  • Reading files in different ways
  • Writing and appending
  • Using with, and working with paths

Prerequisites

Python Strings.

File Modes

Mode Meaning
‘r’ Read (default). Error if missing
‘w’ Write. Creates or overwrites
‘a’ Append to end. Creates if missing
‘x’ Create, error if exists
‘b’ Binary, e.g. ‘rb’ for images
‘+’ Read and write

Writing to a File

Example
with open('notes.txt', 'w', encoding='utf-8') as f:
    f.write('Line 1\n')
    f.write('Line 2\n')

Explanation: with closes the file automatically, even if an error happens. write() does not add a new line, so include \n.

Reading a File

Example
with open('notes.txt', 'r', encoding='utf-8') as f:
    content = f.read()
print(content)
Output
Line 1
Line 2

Reading Line by Line

Example
with open('notes.txt', encoding='utf-8') as f:
    for line in f:
        print(line.strip())

with open('notes.txt', encoding='utf-8') as f:
    lines = f.readlines()
print(lines)

Explanation: Looping over the file reads one line at a time, which works even for very large files. strip() removes the newline.

Output
Line 1
Line 2
['Line 1\n', 'Line 2\n']

Appending

Example
with open('notes.txt', 'a', encoding='utf-8') as f:
    f.write('Line 3\n')

Checking and Deleting Files

Example
import os
if os.path.exists('notes.txt'):
    print(os.path.getsize('notes.txt'), 'bytes')
    os.remove('notes.txt')

Working with Paths

Example
from pathlib import Path
p = Path('data') / 'marks.txt'
p.parent.mkdir(exist_ok=True)
p.write_text('Asha,88\n', encoding='utf-8')
print(p.read_text(encoding='utf-8'))

Explanation: pathlib builds paths that work on both Windows and Linux.

Output
Asha,88

Reading CSV and JSON

Example
import csv, json
with open('marks.csv', newline='', encoding='utf-8') as f:
    for row in csv.reader(f):
        print(row)

with open('config.json', encoding='utf-8') as f:
    config = json.load(f)

Explanation: Use the csv and json modules instead of splitting text by hand. For data analysis, Pandas read_csv() is even easier.

Common Errors

Problem Cause and fix
FileNotFoundError Wrong name or the script runs from a different folder. Print os.getcwd() to check.
UnicodeDecodeError Pass encoding='utf-8' (or the file’s real encoding).
File content disappeared Mode ‘w’ overwrites. Use ‘a’ to add.

Practice Exercises

  1. Count lines and words in a text file.
  2. Copy one file to another.
  3. Save a list of student marks and read it back to find the average.

Interview Questions

Q: Why use with open()?
It closes the file automatically, even on errors.

Q: Difference between w and a?
w overwrites; a appends.

Summary

Open files with with open(path, mode, encoding=…), read with read()/loops, write with w or a, and use pathlib, csv and json for real projects.

Next: Python Exceptions · Python Modules

About Machine Learning

Check Also

Python Inheritance: super(), Method Overriding and MRO

Python inheritance with super(), method overriding, isinstance, multiple inheritance and the method resolution order.