iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python File Handling

Python opens files with the built-in open() function. Use a with block so the file closes automatically — even if an exception is raised.

The pattern

PYTHON
with open('hello.txt', 'r') as f:
    text = f.read()
print(text)

Modes

ModeWhat it does
'r'Read (default). Error if file missing.
'w'Write. Truncates existing file or creates new.
'a'Append to existing file or create new.
'x'Create exclusively — fails if file exists.
'+'Add to any mode for read+write.
'b'Binary mode — bytes, not text.
't'Text mode (default).

Encoding

For text files, pass encoding=:

PYTHON
with open('users.csv', encoding='utf-8') as f:
    text = f.read()

UTF-8 is almost always the right answer.

Binary mode

PYTHON
with open('logo.png', 'rb') as f:
    data = f.read()                  # bytes
print(len(data), 'bytes')

pathlib — modern paths

PYTHON
from pathlib import Path

p = Path('hello.txt')
p.write_text('hello')
print(p.read_text())
print(p.exists(), p.suffix, p.stem)
Tip: Always use with. The file closes immediately when the block exits, which matters on Windows (where you can't reopen a still-open file) and for limited file-handle budgets on Linux.

Example

Example
# In real Python:
# with open('hello.txt', 'w') as f:
#     f.write('hello')
# with open('hello.txt') as f:
#     print(f.read())
print('See the read/write/delete sub-lessons.')
Try it Yourself »

Exercise

Open a file safely using…

open('hello.txt') as f: text = f.read()

Test yourself

Q1. The recommended way to open a file is…
Q2. Mode 'w' opens a file…
Q3. For text files always pass…

Discussion

Loading…