Why files?#
Variables live in memory and disappear when the program ends. Files store data permanently on disk - reports, logs, settings, exported data, user records.
The editor on this page has its own small virtual disk, so you can create and read files right here. On your computer, files are created in the folder where you run the program.
Opening a file#
f = open("filename.txt", mode)
| Mode | Meaning | If file exists | If file missing |
|---|---|---|---|
"r" |
read (default) | read from start | FileNotFoundError |
"w" |
write | erased, then written | created |
"a" |
append | add to the end | created |
"x" |
create | FileExistsError | created |
"r+" |
read and write | - | error |
add "b" |
binary ("rb", "wb") |
for images, PDFs |
Opening a file with "w" deletes everything already in it. Use "a" when you want to keep the old content and add more.
The with statement (always use this)#
with opens the file and closes it automatically when the block ends - even if an error happens:
The old style needs a manual f.close(), which is easy to forget:
f = open("notes.txt")
data = f.read()
f.close() # if an error happens before this line, the file stays open
File के साथ काम करने के 3 कदम हैं: खोलो (open) → पढ़ो/लिखो (read/write) → बंद करो (close)।
with open(...) as f: लिखने से तीसरा कदम (close) अपने आप हो जाता है - block खत्म होते ही file बंद हो जाती है, चाहे बीच में कोई error ही क्यों न आए। इसलिए हमेशा with का इस्तेमाल करें।
Mode याद रखें: "r" = पढ़ना, "w" = नया लिखना (पुराना सब मिट जाएगा!), "a" = आखिर में जोड़ना (पुराना बना रहेगा)।
Writing to a file#
write() takes a string and does not add a newline automatically:
writelines() writes a list of strings (again, add \n yourself):
lines = ["first\n", "second\n"]
with open("out.txt", "w") as f:
f.writelines(lines)
You can also use print(..., file=f), which adds the newline for you.
Reading a file#
| Method | Returns |
|---|---|
f.read() |
the whole file as one string |
f.read(n) |
the next n characters |
f.readline() |
the next line |
f.readlines() |
a list of all lines |
for line in f: |
loops over lines one by one (memory-efficient) |
For big files (log files of several GB), always loop with for line in f: - it reads one line at a time instead of loading the whole file into memory.
Appending#
Handling missing files#
Check before opening:
import os
if os.path.exists("config.txt"):
...
File paths#
open("data.txt") # same folder as where you run Python
open("reports/jan.txt") # sub-folder (use / even on Windows)
open(r"C:\Users\Ravi\Desktop\a.txt") # full Windows path - use a raw string
The modern way is pathlib:
from pathlib import Path
p = Path("reports") / "jan.txt"
p.parent.mkdir(exist_ok=True)
p.write_text("January report")
print(p.read_text())
Text encoding#
Always specify encoding="utf-8" when your file may contain Hindi or other non-English text - especially on Windows:
CSV files (Excel-like data)#
The csv module handles commas, quotes and rows correctly:
JSON files (structured data)#
Summary#
open(name, mode)- modes"r","w"(overwrites),"a"(appends),"x"; add"b"for binary.- Always use
with open(...) as f:- it closes the file automatically. write()needs strings and doesn't add newlines; read withread(),readline(),readlines()orfor line in f.- Handle
FileNotFoundError; useencoding="utf-8"for Hindi/Unicode text. - Use the
csvandjsonmodules for structured data.