Files & Paths
open(), read/write modes, with statement, and pathlib
Skills taught: python.files, python.open, python.pathlib, python.with-statement
Reading files
# Read the entire file
with open('notes.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# Read line by line (memory-efficient)
with open('notes.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip()) # strip() removes the \n
# Read all lines into a list
with open('notes.txt', 'r', encoding='utf-8') as f:
lines = f.readlines() # ['line1\n', 'line2\n', ...]
# Read one line at a time
with open('notes.txt', 'r', encoding='utf-8') as f:
first = f.readline() # first line (including \n)
second = f.readline() # second line
Writing files
# Write (creates or OVERWRITES the file)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!\n')
f.write('Second line\n')
# Append (adds to the end, doesn't erase)
with open('output.txt', 'a', encoding='utf-8') as f:
f.write('Third line\n')
# Write multiple lines at once
lines = ['apple\n', 'banana\n', 'cherry\n']
with open('fruits.txt', 'w', encoding='utf-8') as f:
f.writelines(lines) # no \n added automatically!
# Or use join + write (cleaner)
fruits = ['apple', 'banana', 'cherry']
with open('fruits.txt', 'w', encoding='utf-8') as f:
f.write('\n'.join(fruits))
pathlib — modern path handling
from pathlib import Path
# Create path objects
home = Path.home() # C:\Users\Prashant or /home/prashant
docs = home / 'Documents' # join with /
file = docs / 'notes' / 'todo.txt'
print(file) # full path
print(file.name) # todo.txt
print(file.stem) # todo
print(file.suffix) # .txt
print(file.parent) # .../notes
# Check existence
print(file.exists())
print(file.is_file())
print(file.is_dir())
# Read/write with pathlib
Path('output.txt').write_text('Hello!', encoding='utf-8')
content = Path('output.txt').read_text(encoding='utf-8')
# Find files
for py_file in Path('.').glob('**/*.py'): # all .py files recursively
print(py_file)
# Create directories
Path('data/logs').mkdir(parents=True, exist_ok=True)
Frequently Asked Questions
What happens if I forget to close a file?
The file stays open consuming a file descriptor until the garbage collector reclaims it (or the program exits). On Windows this can prevent other programs from opening the file. Always use 'with open(...) as f:' — it closes the file automatically even if an exception occurs.
How do I read a JSON file?
import json; with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f). This gives you a Python dict/list. To write: json.dump(data, f, indent=2). json.loads()/json.dumps() work with strings instead of files.