Reading and writing files
open() returns a file object; with guarantees it is closed when the block ends, even if an error is raised inside. Never call open() without with — an unclosed file is a leaked handle and, on Windows, a locked file. Modes: "r" read (default), "w" write (truncates!), "a" append, "x" create-or-fail; add "b" for bytes.
You should see
'first line\nsecond line\nthird line\n'
1 first line
2 second line
3 third line
['first line\n', 'second line\n', 'third line\n']notes.txt without reading the whole file into memory (loop over lines, split each).utf-8 every time and the problem never exists.FileNotFoundError: [Errno 2] No such file or directory: 'data/orders.csv'
with open("data/orders.csv") as f:
print(f.read())Traceback (most recent call last):
File "your code", line 1, in <module>
with open("data/orders.csv") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data/orders.csv'A relative path is resolved against the current working directory — the directory you ran python from, not the directory the script lives in. Run the same script from a different folder and the file "disappears". The other causes: a typo, or writing to a directory that does not exist yet (open creates files, never directories).
Build paths from the script's own location, and create parent directories before writing.
from pathlib import Path
HERE = Path(__file__).parent if "__file__" in globals() else Path(".")
data = HERE / "data" / "orders.csv"
data.parent.mkdir(parents=True, exist_ok=True)
data.write_text("id,total\n1,9.99\n", encoding="utf-8")
print(data.read_text(encoding="utf-8"))