Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Python File Handling
Python Beginner FREE

File Handling

Lesson 1 of 14 Beginner Interactive

Use open() with modes: "r", "w", "a", "x".

Context Manager

The with statement ensures files are properly closed.

JSON Module

json.dump() and json.load() for structured data.

Syntax

PYTHON
with open("file.txt", "r") as f:
    content = f.read()

with open("out.txt", "w") as f:
    f.write("Hello
")

import json
data = {"name": "Alice"}
with open("data.json", "w") as f:
    json.dump(data, f)
Python File Handling
PYTHON
# Writing files
with open("notes.txt", "w") as f:
    f.write("Line 1
")
    f.write("Line 2
")

# Reading files
with open("notes.txt", "r") as f:
    content = f.read()
print("Content:", repr(content))

# Read line by line
with open("notes.txt", "r") as f:
    for line in f:
        print("Line:", line.strip())

# Append
with open("notes.txt", "a") as f:
    f.write("Line 3
")

# With block auto-closes the file!
File Operations
PYTHON
# Write to file
with open("example.txt", "w") as f:
    f.write("Hello, World!
")
    f.write("Line two
")

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

# Read line by line
with open("example.txt", "r") as f:
    for line in f:
        print(line.strip())

Practice

1
Exercise

Copy a file converting text to uppercase.

Answer
with open("src.txt") as s:
    with open("dst.txt","w") as d:
        d.write(s.read().upper())

Quick Quiz

1

Why use the with statement?

Ensures files are closed automatically.

Interview Questions

read() returns entire file. readline() returns one line. readlines() returns list of lines.