How to Read and Write CSV, JSON and Text Files in Python (with open and with)
P9.1 File Paths and the Working Folder in Python
Why. Most "file not found" errors are path problems. Python looks for files in the current working folder unless you give a full path.
What.
- Working folder — where Python is running now.
os.getcwd()shows it. - Relative path —
data/sales.csv(from the working folder). - Absolute path — the full path, like
C:/Users/you/data/sales.csv. pathlib.Path— a modern, safe way to build paths on Windows and Mac.
How.
Find and check a file
- Print the working folder.
- List files with
os.listdir(). - Build the path with
Path("data") / "sales.csv". - Check it exists with
.exists().
Worked example A — Where am I?.
Step 1 — What we do. We check that a file exists before opening it.
Step 2 — Make the input file sales.csv in the same folder as your code:
date,store,item,qty,price
2026-03-01,Pune,Milk,3,56
2026-03-01,Mumbai,Bread,2,40
2026-03-02,Pune,Eggs,1,84
2026-03-02,Nagpur,Milk,5,56
About this data: each line after the first is one sale. The first line is the header: date of sale, store city, item name, qty (units sold) and price (₹ per unit).
Step 3 — Type and run this code.
from pathlib import Path
p = Path("sales.csv")
print(p.exists())
print(p.suffix)
Step 4 — Output you should see.
True
.csv
Step 5 — What it means. exists() is True because the file is in the working folder. .suffix gives the extension.
Worked example B — Build a path safely.
Step 1 — What we do. Paths are joined with / using pathlib; it works on Windows and Mac.
Step 2 — Type and run this code.
from pathlib import Path
p = Path("reports") / "2026" / "march.csv"
print(p.as_posix())
print(p.name, p.stem)
Step 3 — Output you should see.
reports/2026/march.csv
march.csv march
Step 4 — What it means. No worry about \ vs /. .name is the file name and .stem is the name without the extension.
Ravindra Bagale's Tip
On Windows, write paths with forward slashes C:/data/file.csv or use pathlib. Backslashes inside normal strings cause strange bugs.
Ravindra Bagale's Tip – मराठी
Windows वर paths forward slash ने लिहा C:/data/file.csv किंवा pathlib वापरा. साध्या strings मधले backslashes विचित्र bugs आणतात.
Ravindra Bagale's Tip – हिंदी
Windows पर paths forward slash से लिखो C:/data/file.csv या pathlib इस्तेमाल करो. सादी strings में backslashes अजीब bugs लाते हैं.