File handling in Python allows you to create, read, write, and modify files. Python provides built-in functions and methods that make working with files simple and powerful.
🔹 1. Opening a File
Use the built-in open() function:
file = open("example.txt", "r")
Modes in open()
| Mode | Meaning | Description |
|---|---|---|
"r" |
Read | Default mode. Opens file for reading (error if not found). |
"w" |
Write | Creates/overwrites file. |
"a" |
Append | Writes at end (does not delete content). |
"x" |
Create | Creates file (error if exists). |
"b" |
Binary | Use for images, PDFs, etc. |
"t" |
Text | Default mode for text files. |
"r+" |
Read + Write | Reads and writes. |
Example:
f = open("data.txt", "w")
🔹 2. Reading a File
Read entire file
f = open("example.txt", "r")
content = f.read()
print(content)
f.close()
Read line by line
f = open("example.txt", "r")
for line in f:
print(line)
f.close()
Read specific number of characters
f.read(10)
🔹 3. Writing to a File
Write text
f = open("example.txt", "w")
f.write("Hello, world!")
f.close()
Append text
f = open("example.txt", "a")
f.write("\nNew line added.")
f.close()
🔹 4. Using with statement (BEST PRACTICE)
It automatically closes the file.
with open("example.txt", "r") as f:
print(f.read())
🔹 5. Other Useful File Methods
| Method | Description |
|---|---|
f.read() |
Reads whole file |
f.readline() |
Reads a single line |
f.readlines() |
Returns list of all lines |
f.write() |
Writes a string |
f.seek(pos) |
Move cursor to position |
f.tell() |
Shows current cursor position |
f.close() |
Closes the file |
🔹 6. File Handling Example
Writing and reading a file
# Writing
with open("student.txt", "w") as f:
f.write("Name: John\nAge: 20")
# Reading
with open("student.txt", "r") as f:
data = f.read()
print(data)
🔹 7. Handling Exceptions
try:
with open("data.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File does not exist!")
If you'd like, I can provide:
✅ Exercises
✅ A mini-project (like a notes app)
✅ File handling with JSON, CSV, or binary files
Would you like examples?
Sure! Here’s a deeper and more advanced explanation of file handling in Python, including handling different file types, directories, and practical examples.
🔶 1. Reading Files in Different Ways
1.1 read() — entire content
with open("data.txt", "r") as f:
content = f.read()
print(content)
1.2 readline() — one line at a time
with open("data.txt", "r") as f:
line = f.readline()
while line:
print(line, end="")
line = f.readline()
1.3 readlines() — returns list of all lines
with open("data.txt", "r") as f:
lines = f.readlines()
print(lines)
🔶 2. Writing Files - Advanced
2.1 Writing multiple lines
lines = ["Python\n", "Java\n", "C++\n"]
with open("lang.txt", "w") as f:
f.writelines(lines)
2.2 Writing only if file does NOT exist (x mode)
with open("unique.txt", "x") as f:
f.write("This file is created only once.")
🔶 3. File Pointer (Cursor) Control
3.1 seek() — move pointer
with open("sample.txt", "r") as f:
f.seek(5)
print(f.read())
3.2 tell() — get current position
with open("sample.txt", "r") as f:
print(f.tell())
🔶 4. Working With Different File Types
4.1 Handling JSON Files
import json
data = {"name": "Alice", "age": 22}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
with open("data.json", "r") as f:
content = json.load(f)
print(content)
4.2 Handling CSV Files
import csv
# Writing
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["John", 20])
# Reading
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
4.3 Handling Binary Files (images, pdf, etc.)
# Copy an image
with open("photo.jpg", "rb") as src:
with open("copy.jpg", "wb") as dst:
dst.write(src.read())
🔶 5. Checking if File Exists Before Opening
import os
if os.path.exists("myfile.txt"):
print("File exists!")
else:
print("File not found!")
🔶 6. Working with Directories
6.1 Create a folder
import os
os.mkdir("new_folder")
6.2 List files in a directory
print(os.listdir("."))
6.3 Remove a file
os.remove("old_file.txt")
6.4 Remove a folder
os.rmdir("new_folder")
🔶 7. Exception Handling in File Operations
try:
with open("abc.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("The file does not exist!")
except PermissionError:
print("You don't have permission to access this file.")
finally:
print("Done!")
🔶 8. Practical Mini-Project Example
📌 Simple Note Writing Program
def write_note():
note = input("Enter your note: ")
with open("notes.txt", "a") as f:
f.write(note + "\n")
print("Note saved!")
def show_notes():
with open("notes.txt", "r") as f:
print(f.read())
while True:
print("\n1. Write Note")
print("2. Show Notes")
print("3. Exit")
choice = input("Choose: ")
if choice == "1":
write_note()
elif choice == "2":
show_notes()
else:
break
Here’s a deeper and more advanced explanation of file handling in Python, including handling different file types, directories, and practical examples.
🔶 1. Reading Files in Different Ways
1.1 read() — entire content
with open("data.txt", "r") as f:
content = f.read()
print(content)
1.2 readline() — one line at a time
with open("data.txt", "r") as f:
line = f.readline()
while line:
print(line, end="")
line = f.readline()
1.3 readlines() — returns list of all lines
with open("data.txt", "r") as f:
lines = f.readlines()
print(lines)
🔶 2. Writing Files - Advanced
2.1 Writing multiple lines
lines = ["Python\n", "Java\n", "C++\n"]
with open("lang.txt", "w") as f:
f.writelines(lines)
2.2 Writing only if file does NOT exist (x mode)
with open("unique.txt", "x") as f:
f.write("This file is created only once.")
🔶 3. File Pointer (Cursor) Control
3.1 seek() — move pointer
with open("sample.txt", "r") as f:
f.seek(5)
print(f.read())
3.2 tell() — get current position
with open("sample.txt", "r") as f:
print(f.tell())
🔶 4. Working With Different File Types
4.1 Handling JSON Files
import json
data = {"name": "Alice", "age": 22}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
with open("data.json", "r") as f:
content = json.load(f)
print(content)
4.2 Handling CSV Files
import csv
# Writing
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["John", 20])
# Reading
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
4.3 Handling Binary Files (images, pdf, etc.)
# Copy an image
with open("photo.jpg", "rb") as src:
with open("copy.jpg", "wb") as dst:
dst.write(src.read())
🔶 5. Checking if File Exists Before Opening
import os
if os.path.exists("myfile.txt"):
print("File exists!")
else:
print("File not found!")
🔶 6. Working with Directories
6.1 Create a folder
import os
os.mkdir("new_folder")
6.2 List files in a directory
print(os.listdir("."))
6.3 Remove a file
os.remove("old_file.txt")
6.4 Remove a folder
os.rmdir("new_folder")
🔶 7. Exception Handling in File Operations
try:
with open("abc.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("The file does not exist!")
except PermissionError:
print("You don't have permission to access this file.")
finally:
print("Done!")
🔶 8. Practical Mini-Project Example
📌 Simple Note Writing Program
def write_note():
note = input("Enter your note: ")
with open("notes.txt", "a") as f:
f.write(note + "\n")
print("Note saved!")
def show_notes():
with open("notes.txt", "r") as f:
print(f.read())
while True:
print("\n1. Write Note")
print("2. Show Notes")
print("3. Exit")
choice = input("Choose: ")
if choice == "1":
write_note()
elif choice == "2":
show_notes()
else:
break
If you want, I can also explain:
✅ File handling interview questions
✅ Buffering & performance
✅ Working with ZIP files
✅ Reading large files efficiently
✅ Practice problems
Would you like more?

0 Comments