CSIP12.in
Back to List
Calculating...
UNIT 1 : CH 4 Dec 09, 2025

File Handling in Python

### Introduction to Files

Files are used to store data permanently on secondary storage devices. Python provides built-in functions to create, read, update, and delete files.

### Types of Files

1. **Text Files**: Store data as plain text with newline characters separating lines
2. **Binary Files**: Store data in binary format, more compact and faster to process
3. **CSV Files**: Special text files with comma-separated values, used for tabular data

### File Operations

The basic file operations include:

- **Creating** a file
- **Opening** a file
- **Reading** from a file
- **Writing** to a file
- **Closing** a file
- **Deleting** a file

### File Modes

Different modes are used while opening files:

- **'r'**: Read mode (default), file must exist
- **'w'**: Write mode, creates new file or overwrites existing
- **'a'**: Append mode, adds data to end of file
- **'r+'**: Read and write mode
- **'w+'**: Write and read mode
- **'a+'**: Append and read mode
- **'rb', 'wb', 'ab'**: Binary modes

---

## 3. Important Points

- Always close a file after operations to free up system resources
- If file is not closed properly, data may be lost
- File pointer moves automatically after read/write operations
- Text files use `read()`, `readline()`, `readlines()` for reading
- Binary files require the `pickle` module for reading/writing
- CSV files require the `csv` module for proper handling
- Use `with` statement for automatic file closing
- Binary files are more efficient for storing complex data structures
- File path can be absolute or relative
- Default file opening mode is 'r' (read)

---

## 4. Syntax

### Opening and Closing Files

```python
# Opening a file
file_object = open("filename", "mode")

# Closing a file
file_object.close()

# Using with statement (automatic closing)
with open("filename", "mode") as file_object:
# file operations
pass
```

### Text File Operations

```python
# Writing to a text file
f = open("data.txt", "w")
f.write("Hello World\n")
f.close()

# Reading from a text file
f = open("data.txt", "r")
content = [f.read](http://f.read)() # reads entire file
f.close()

# Reading line by line
f = open("data.txt", "r")
line = f.readline() # reads one line
f.close()

# Reading all lines as a list
f = open("data.txt", "r")
lines = f.readlines() # returns list of lines
f.close()
```

### Binary File Operations (Pickling)

```python
import pickle

# Writing to binary file (Pickling)
f = open("data.dat", "wb")
data = [1, 2, 3, 4, 5]
pickle.dump(data, f)
f.close()

# Reading from binary file (Unpickling)
f = open("data.dat", "rb")
data = pickle.load(f)
f.close()
```

### CSV File Operations

```python
import csv

# Writing to CSV file
f = open("data.csv", "w", newline='')
writer = csv.writer(f)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Amit', 18, 'Delhi'])
f.close()

# Reading from CSV file
f = open("data.csv", "r")
reader = csv.reader(f)
for row in reader:
print(row)
f.close()
```

### flush() Function

```python
f = open("data.txt", "w")
f.write("Important data")
f.flush() # forces data to be written to disk immediately
# more operations
f.close()
```

---

## 5. Examples

### Example 1: Creating and Writing to Text File

```python
# Program to write student names to a file
f = open("students.txt", "w")
f.write("Rahul\n")
f.write("Priya\n")
f.write("Amit\n")
f.close()
print("Data written successfully")
```

### Example 2: Reading from Text File

```python
# Program to read and display file content
f = open("students.txt", "r")
content = [f.read](http://f.read)()
print(content)
f.close()
```

### Example 3: Counting Lines in a File

```python
# Program to count number of lines
f = open("students.txt", "r")
lines = f.readlines()
print("Number of lines:", len(lines))
f.close()
```

### Example 4: Binary File - Storing List of Numbers

```python
import pickle

# Writing list to binary file
f = open("numbers.dat", "wb")
numbers = [10, 20, 30, 40, 50]
pickle.dump(numbers, f)
f.close()

# Reading list from binary file
f = open("numbers.dat", "rb")
data = pickle.load(f)
print("Numbers:", data)
f.close()
```

### Example 5: Binary File - Storing Dictionary

```python
import pickle

# Writing dictionary to binary file
f = open("student.dat", "wb")
student = {'Name': 'Rahul', 'Roll': 101, 'Marks': 95}
pickle.dump(student, f)
f.close()

# Reading dictionary from binary file
f = open("student.dat", "rb")
data = pickle.load(f)
print(data)
f.close()
```

### Example 6: CSV File - Student Records

```python
import csv

# Writing student records
f = open("students.csv", "w", newline='')
writer = csv.writer(f)
writer.writerow(['Roll No', 'Name', 'Marks'])
writer.writerow([101, 'Amit', 85])
writer.writerow([102, 'Priya', 92])
writer.writerow([103, 'Rahul', 78])
f.close()

# Reading and displaying records
f = open("students.csv", "r")
reader = csv.reader(f)
for row in reader:
print(row)
f.close()
```

### Example 7: Searching in Binary File

```python
import pickle

def search_record(roll):
f = open("students.dat", "rb")
found = False
try:
while True:
student = pickle.load(f)
if student['Roll'] == roll:
print("Record found:", student)
found = True
break
except EOFError:
pass
f.close()
if not found:
print("Record not found")

# Usage
search_record(102)
```

### Example 8: Using with Statement

```python
# Recommended way - automatic file closing
with open("data.txt", "r") as f:
content = [f.read](http://f.read)()
print(content)
# File automatically closed after with block
```

---

## 6. Tables / Diagrams

### File Opening Modes

| Mode | Description | File Must Exist? | Creates New File? | Overwrites? |
| --- | --- | --- | --- | --- |
| 'r' | Read only | Yes | No | No |
| 'w' | Write only | No | Yes | Yes |
| 'a' | Append | No | Yes | No |
| 'r+' | Read and Write | Yes | No | No |
| 'w+' | Write and Read | No | Yes | Yes |
| 'a+' | Append and Read | No | Yes | No |
| 'rb' | Read binary | Yes | No | No |
| 'wb' | Write binary | No | Yes | Yes |
| 'ab' | Append binary | No | Yes | No |

### Text File vs Binary File vs CSV File

| Feature | Text File | Binary File | CSV File |
| --- | --- | --- | --- |
| Format | Plain text (ASCII/Unicode) | Binary (0s and 1s) | Text with commas |
| Human Readable | Yes | No | Yes |
| Module Required | Built-in | pickle | csv |
| Extension | .txt, .py | .dat, .bin | .csv |
| Storage | Less efficient | More efficient | Tabular data |
| Speed | Slower | Faster | Moderate |
| Use Case | Simple text data | Complex objects | Tabular records |

### File Methods

| Method | Description | Example |
| --- | --- | --- |
| `read()` | Reads entire file | [`f.read](http://f.read)()` |
| `read(n)` | Reads n characters | [`f.read](http://f.read)(10)` |
| `readline()` | Reads one line | `f.readline()` |
| `readlines()` | Reads all lines as list | `f.readlines()` |
| `write(s)` | Writes string s | `f.write("text")` |
| `writelines(L)` | Writes list of strings | `f.writelines(list)` |
| `close()` | Closes file | `f.close()` |
| `flush()` | Flushes buffer | `f.flush()` |
| `seek(n)` | Moves pointer to position n | [`f.seek](http://f.seek)(0)` |
| `tell()` | Returns current position | `f.tell()` |

---

## 7. Common Errors / Misconceptions

### Error 1: FileNotFoundError

```python
# Wrong - file doesn't exist
f = open("xyz.txt", "r") # Error if file doesn't exist

# Correct - use appropriate mode or check existence
import os
if os.path.exists("xyz.txt"):
f = open("xyz.txt", "r")
else:
print("File not found")
```

### Error 2: Forgetting to Close File

```python
# Wrong - file not closed
f = open("data.txt", "w")
f.write("Hello")
# File not closed - data may be lost

# Correct - always close
f = open("data.txt", "w")
f.write("Hello")
f.close()

# Best - use with statement
with open("data.txt", "w") as f:
f.write("Hello")
```

### Error 3: Writing to File Opened in Read Mode

```python
# Wrong
f = open("data.txt", "r")
f.write("Hello") # Error!
f.close()

# Correct
f = open("data.txt", "w")
f.write("Hello")
f.close()
```

### Error 4: Not Using newline='' in CSV

```python
# Wrong - extra blank lines in Windows
f = open("data.csv", "w")
writer = csv.writer(f)

# Correct
f = open("data.csv", "w", newline='')
writer = csv.writer(f)
```

### Error 5: EOFError in Binary Files

```python
# Wrong - doesn't handle end of file
import pickle
f = open("data.dat", "rb")
while True:
data = pickle.load(f) # Will raise EOFError at end
print(data)

# Correct - handle EOFError
import pickle
f = open("data.dat", "rb")
try:
while True:
data = pickle.load(f)
print(data)
except EOFError:
pass
f.close()
```

### Misconception 1: File Pointer Position

**Wrong Understanding**: File pointer always starts at beginning after write operations

**Correct Understanding**: File pointer moves to the end after writing. Use `seek(0)` to move to beginning.

### Misconception 2: Append vs Write Mode

**Wrong Understanding**: Append mode ('a') and write mode ('w') are the same

**Correct Understanding**: Write mode overwrites existing content, append mode adds to the end

### Misconception 3: Binary Files Store Only Numbers

**Wrong Understanding**: Binary files can only store numbers

**Correct Understanding**: Binary files can store any Python object (lists, dictionaries, tuples, etc.)

---

## 8. Exam-Oriented Short Notes

### Quick Revision Points

**File Basics**

- File is permanent storage on disk
- Three types: Text, Binary, CSV
- Must open before use, close after use
- File handle is returned by `open()`

**Text Files**

- Store data as plain text
- Methods: `read()`, `readline()`, `readlines()`, `write()`, `writelines()`
- Human readable
- Larger size compared to binary

**Binary Files**

- Store data in binary format
- Require `import pickle`
- Pickling: `pickle.dump(object, file)`
- Unpickling: `pickle.load(file)`
- More efficient and faster
- Can store complex Python objects

**CSV Files**

- Store tabular data with commas
- Require `import csv`
- Writer: `csv.writer(file)`
- Reader: `csv.reader(file)`
- Use `newline=''` in Windows
- Methods: `writerow()`, `writerows()`

**File Modes - Must Remember**

- 'r': Read (default), file must exist
- 'w': Write, overwrites if exists
- 'a': Append, adds to end
- 'b': Binary (rb, wb, ab)

**Important Functions**

- `open()`: Opens file
- `close()`: Closes file
- `read()`: Reads entire file
- `readline()`: Reads one line
- `readlines()`: Returns list of all lines
- `write()`: Writes string to file
- `flush()`: Forces immediate write to disk
- `seek()`: Moves file pointer
- `tell()`: Returns pointer position

**with Statement**

```python
with open("file.txt", "r") as f:
data = [f.read](http://f.read)()
# Automatically closes file
```

**File Pointer**

- Indicates current position in file
- Moves automatically after read/write
- `seek(0)`: Move to beginning
- `seek(0, 2)`: Move to end
- `tell()`: Get current position

**Standard Streams**

- `stdin`: Standard input (keyboard)
- `stdout`: Standard output (screen)
- `stderr`: Standard error (screen)

**Exception Handling**

- Use try-except for file operations
- `FileNotFoundError`: When file doesn't exist
- `EOFError`: When end of binary file reached
- `PermissionError`: When no access rights

**Best Practices**

- Always close files or use `with`
- Check file existence before opening in read mode
- Use appropriate file mode
- Handle exceptions properly
- Use binary files for complex data
- Use CSV for tabular data
- Flush buffer for critical data

**Common Exam Questions Topics**

1. Difference between text and binary files
2. File opening modes
3. Pickling and unpickling
4. CSV file operations
5. Searching in files
6. Counting words/lines/characters
7. Updating records in binary files
8. File pointer significance
9. Difference between `write()` and `writelines()`
10. Difference between `read()`, `readline()`, `readlines()`

**Important Code Patterns for Exam**

```python
# Pattern 1: Read entire file
with open("file.txt", "r") as f:
content = [f.read](http://f.read)()

# Pattern 2: Read line by line
with open("file.txt", "r") as f:
for line in f:
print(line.strip())

# Pattern 3: Write multiple records (Binary)
import pickle
with open("file.dat", "wb") as f:
for record in records:
pickle.dump(record, f)

# Pattern 4: Read multiple records (Binary)
import pickle
with open("file.dat", "rb") as f:
try:
while True:
record = pickle.load(f)
print(record)
except EOFError:
pass

# Pattern 5: CSV operations
import csv
with open("file.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age'])
```

**Memory Tips**

- **RAW**: Read-Append-Write (file modes)
- **PUP**: Pickle-Unpickle-Python (binary files)
- **CROW**: CSV-Reader-Objects-Writer
- **SORT**: Seek-Opens-Read-Tell (file pointer operations)