Skip to content
Home Tutorials Roadmaps Courses Classroom Training Blog
Log in Join free
Python Beginner Free

File Handling

Lesson 11 of 14 · File & Modules 79%

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\n")
    f.write("Line 2\n")

# 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\n")

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

# 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.

Choose an answer to continue.

Interview Questions

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

Up next

Modules & Packages

Lesson 12 of 14 · File & Modules