8. File Handling in Python

File handling allows Python programs to:

  • Read data from files
  • Write data to files
  • Store information permanently

Python provides built-in functions for file operations.


Opening and Closing Files

Use the open() function to open a file.


Syntax

file = open("filename", "mode")

Parameters:

  • filename → name of file
  • mode → operation mode

Example

file = open("data.txt", "r")

Closing Files

Always close files after use.

file.close()

Using with Statement

Recommended method.

Automatically closes file.

with open("data.txt", "r") as file:
content = file.read()

print(content)

Reading Files


1. read()

Reads entire file.

Example

with open("data.txt", "r") as file:
data = file.read()

print(data)

2. readline()

Reads one line at a time.

with open("data.txt", "r") as file:
line = file.readline()

print(line)

3. readlines()

Reads all lines into a list.

with open("data.txt", "r") as file:
lines = file.readlines()

print(lines)

Reading File Using Loop

with open("data.txt", "r") as file:
for line in file:
print(line.strip())

Writing Files


1. Write Mode (w)

Creates new file or overwrites existing file.

with open("data.txt", "w") as file:
file.write("Hello Python")

2. Append Mode (a)

Adds data at end of file.

with open("data.txt", "a") as file:
file.write("\nNew Line")

Writing Multiple Lines

lines = ["Python\n", "Java\n", "C++\n"]

with open("languages.txt", "w") as file:
file.writelines(lines)

File Modes

ModeDescription
rRead
wWrite
aAppend
xCreate file
bBinary mode
tText mode
r+Read and write

Examples

open("file.txt", "r")
open("file.txt", "w")
open("file.txt", "a")

Binary File Example

with open("image.jpg", "rb") as file:
data = file.read()

File Pointer Methods


tell()

Returns current file position.

with open("data.txt", "r") as file:
print(file.tell())

seek()

Moves file pointer.

with open("data.txt", "r") as file:
file.seek(5)
print(file.read())

Working with CSV Files

CSV = Comma Separated Values

Python provides the csv module.


Import CSV Module

import csv

Writing CSV File

import csv

data = [
["Name", "Age"],
["Aditya", 25],
["Rahul", 22]
]

with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)

writer.writerows(data)

Reading CSV File

import csv

with open("students.csv", "r") as file:
reader = csv.reader(file)

for row in reader:
print(row)

Output:

['Name', 'Age']
['Aditya', '25']
['Rahul', '22']

Using DictWriter

import csv

with open("employees.csv", "w", newline="") as file:

fields = ["name", "salary"]

writer = csv.DictWriter(file, fieldnames=fields)

writer.writeheader()

writer.writerow({
"name": "Aditya",
"salary": 50000
})

Working with JSON Files

JSON = JavaScript Object Notation

Used for storing and exchanging data.

Python provides the json module.


Import JSON Module

import json

Convert Python Object to JSON

Use json.dump().

import json

student = {
"name": "Aditya",
"age": 25
}

with open("student.json", "w") as file:
json.dump(student, file)

Read JSON File

Use json.load().

import json

with open("student.json", "r") as file:
data = json.load(file)

print(data)

Convert Dictionary to JSON String

import json

data = {
"language": "Python"
}

json_data = json.dumps(data)

print(json_data)

Convert JSON String to Dictionary

import json

text = '{"name":"Aditya","age":25}'

data = json.loads(text)

print(data)

Pretty Print JSON

import json

student = {
"name": "Aditya",
"age": 25
}

print(json.dumps(student, indent=4))

Exception Handling in File Operations

try:
with open("data.txt", "r") as file:
print(file.read())

except FileNotFoundError:
print("File not found")

Practical Example

Copy File Content

with open("source.txt", "r") as source:
content = source.read()

with open("destination.txt", "w") as destination:
destination.write(content)

print("File copied successfully")