xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Files

Objects and errors5 min readLesson 3 of 3

Use with so the file closes even if a line in the block raises.

python
with open("notes.txt", "w", encoding="utf-8") as handle:
    handle.write("first line\n")

with open("notes.txt", encoding="utf-8") as handle:
    text = handle.read()

with open("notes.txt", encoding="utf-8") as handle:
    for line in handle:
        print(line.rstrip())

Always pass encoding="utf-8". The default depends on the operating system, which is how scripts work on one machine and break on another.

For paths, prefer pathlib:

python
from pathlib import Path

data = Path("data")
data.mkdir(exist_ok=True)
for path in data.glob("*.txt"):
    print(path.name, path.stat().st_size)

Read the whole file only when it is small; otherwise loop over the handle, which reads one line at a time.