⚡0 XP🔥0

File Handling

Lesson 25 of 33 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Read and write text files with open(), file modes, the with statement, reading line by line, appending, and working with CSV and JSON files.

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.

Did you know?

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
Common Mistake

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:

▶ Try it YourselfPython
Ctrl + Enter to run

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:

▶ Try it YourselfPython
Ctrl + Enter to run

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)
▶ Try it YourselfPython
Ctrl + Enter to run
Tip

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#

▶ Try it YourselfPython
Ctrl + Enter to run

Handling missing files#

▶ Try it YourselfPython
Ctrl + Enter to run

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:

▶ Try it YourselfPython
Ctrl + Enter to run

CSV files (Excel-like data)#

The csv module handles commas, quotes and rows correctly:

▶ Try it YourselfPython
Ctrl + Enter to run

JSON files (structured data)#

▶ Try it YourselfPython
Ctrl + Enter to run

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 with read(), readline(), readlines() or for line in f.
  • Handle FileNotFoundError; use encoding="utf-8" for Hindi/Unicode text.
  • Use the csv and json modules for structured data.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Write and read back

Write the three names in names to a file students.txt, one per line. Then open the file again, read it, and print how many lines it has.

Expected output:
3
2

Total from a file

The code creates sales.txt with one amount per line. Read it and print the total of all amounts.

Expected output:
4750
3

Append a log entry

Write a function log(message) that appends the message as a new line to app.log. The calls below should leave exactly two lines in the file, and the program prints the file content.

Expected output:
Server started
User logged in

Quick Quiz

Q1.

Which mode opens a file for writing and erases existing content?

Q2.

What is the main advantage of with open(...) as f:?

Q3.

What does f.readlines() return?

Q4.

What happens if you open a missing file in "r" mode?

Q5.

Does f.write(100) work?