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.
