CBSETest.comby Bimal Publications

Need help with File Handling in Python?

Practice Tests
Class 12 · Computer Science NCERT Class 12 Computer Science · Ch. 24 min read · 15 questions

File Handling in Python

Computer Science

File Handling in Python

Programs usually need to store data permanently so it survives beyond program execution. File handling provides the mechanism to read from and write to files stored on secondary storage (hard disk, SSD). Python provides simple built-in functions to work with both text files and binary files.

Types of Files

Text Files store data as human-readable characters encoded in ASCII or Unicode (UTF-8). Each line ends with a newline character (\n). Examples: .txt, .csv, .py files.

Binary Files store data in the same format it is stored in memory (bytes). They are not human-readable directly. Examples: .jpg, .mp3, .pdf, .exe, .dat files.

Opening a File

Python uses the built-in open() function:

```
fileobject = open(filename, mode)
```

File Opening Modes:

| Mode | Meaning |
|------|---------|
| 'r' | Read (default). File must exist. |
| 'w' | Write. Creates file or OVERWRITES if exists. |
| 'a' | Append. Creates file or adds to end. |
| 'r+' | Read and Write. File must exist. |
| 'rb' | Read binary |
| 'wb' | Write binary |
| 'ab' | Append binary |

Reading from a Text File

  • read() — reads the entire file as one string.
  • readline() — reads one line at a time (including \n).
  • readlines() — reads all lines and returns a list of strings.

Iterating directly over a file object reads line by line — memory-efficient for large files.

Writing to a Text File

  • write(string) — writes a string to the file; does NOT add \n automatically.
  • writelines(list) — writes all strings in a list; does NOT add newlines between items.

Closing a File

Always close the file using close() to flush buffers and free system resources. The better practice is to use the with statement, which automatically closes the file even if an exception occurs:

```
with open('data.txt', 'r') as f:
content = f.read()
# file is automatically closed here
```

File Pointer and seek/tell

The file pointer marks the current read/write position.

  • tell() — returns the current byte position of the pointer.
  • seek(offset, from) — moves the pointer. from: 0=start, 1=current, 2=end.

Binary Files and the pickle Module

Binary files store Python objects as byte streams using the pickle module:

  • pickle.dump(object, file) — serialises and writes an object.
  • pickle.load(file) — reads and deserialises an object.

Open binary files with modes 'wb' / 'rb'.

CSV Files

A CSV (Comma Separated Values) file stores tabular data as plain text with commas separating values. Python's csv module simplifies reading and writing:

  • csv.reader(file) — returns an iterator of rows (each row is a list).
  • csv.writer(file) — creates a writer; use writer.writerow(list) to write a row.

Worked Examples

Example 1 — Writing to a file:
```
with open('notes.txt', 'w') as f:
f.write('Line one\n')
f.write('Line two\n')
```

Example 2 — Reading all lines:
```
with open('notes.txt', 'r') as f:
for line in f:
print(line, end='')
```

Example 3 — pickle:
```
import pickle
data = {'name': 'Riya', 'marks': 95}
with open('record.dat', 'wb') as f:
pickle.dump(data, f)
```

Common mistakes

  • Not closing the file — use with statement to avoid this.
  • Opening in 'w' mode by mistake — this ERASES existing content; use 'a' to append.
  • Forgetting to add \n in write() — write() does not add newlines; you must include them explicitly.
  • Reading a binary file in text mode — always use 'rb' for binary files.

Summary

File handling involves opening a file in the right mode, performing read/write operations, and closing it (best done via the with statement). Python supports text files (read/write/append), binary files (via pickle), and CSV files (via the csv module). The file pointer tracks position and can be moved with seek().

Practice Problems

15 questions with instant feedback.

Question 1 of 15Score 0

Which function is used to open a file in Python?