File handling in Python is used to create, read, write, append, and manage files stored permanently on your storage disk (HDD or SSD). Without file handling, all data variables disappear from RAM the moment your program stops running.
1. Why File Handling?
| Without File Handling (Stored only in RAM) | With File Handling (Saved permanently to Disk) |
|---|---|
| Student or customer data disappears when program closes. | Store employee, student, or inventory records permanently. |
| User login states and auth tokens are lost. | Persist configuration, login tokens, and activity logs. |
| Reports cannot be stored or shared. | Generate and save text, CSV, JSON, and PDF files. |
| Calculated results cannot be restored. | Save Machine Learning models, weights, and metrics. |
2. Types of Files
- Text Files (.txt, .csv, .py): Contain human-readable characters encoded in standard formats like UTF-8.
- Binary Files (.jpg, .mp3, .pdf, .bin): Contain raw machine bytes (0s and 1s) and cannot be edited in a regular text editor.
3. Opening & Closing Files
To interact with a file in Python, use the open() function:
file_object = open("filename.txt", "mode")
File Modes Reference
| Mode | Action | Pointer Position | If File Does Not Exist |
|---|---|---|---|
r | Read only (Default) | Beginning | Throws FileNotFoundError |
w | Write only (Overwrites/Deletes old content) | Beginning | Creates new file |
a | Append (Adds to end of file) | End | Creates new file |
x | Exclusive creation | Beginning | Throws FileExistsError |
rb / wb | Read / Write in Binary | Beginning | - |
r+ | Read and Write mode | Beginning | Throws FileNotFoundError |
w+ | Write and Read (Deletes old content) | Beginning | Creates new file |
a+ | Append and Read | End | Creates new file |
4. Controlling the File Pointer: tell() & seek()
- tell(): Returns the current byte index position of the cursor inside the file.
- seek(offset): Repositions the cursor directly to the specified byte index.
with open("sample.txt", "w+") as f:
f.write("Hello Python")
print("Pointer position:", f.tell()) # Output: 12
f.seek(0) # Reset cursor back to start (index 0)
print("Content:", f.read()) # Output: Hello Python
5. Top 10 Technical Interview Questions & Answers
1. What is file handling and why do we use it?
File handling allows programs to read from and write to storage devices permanently. Without it, program data vanishes from RAM when execution ends.
2. What is the difference between 'r', 'w', and 'a' modes?
'r' (Read): Opens an existing file for reading. Fails if missing.
'w' (Write): Overwrites existing content. Creates a new file if missing.
'a' (Append): Writes data at the end without erasing old data. Creates a new file if missing.
3. Difference between read(), readline(), and readlines()?
read() reads the whole file as one single string. readline() reads one line at a time. readlines() reads all lines and returns them as a Python list of strings.
4. Difference between write() and writelines()?
write() accepts a single string. writelines() accepts an iterable (like a list of strings) and writes them consecutively without adding newlines automatically.
5. Why is 'with open()' recommended over open()...close()?
The with statement handles context management automatically. It closes the file cleanly even if the program throws an unexpected runtime error.
6. What are seek() and tell() used for?
tell() informs you where the read/write cursor is currently located. seek(pos) jumps the cursor to an exact byte position (e.g., seek(0) jumps to the file start).
7. What is the difference between Text and Binary mode?
Text mode decodes raw bytes into characters using encodings like UTF-8. Binary mode handles raw bytes directly, which is required for images, audio, and compiled binaries.
8. What happens if you open an existing file in 'w' mode?
The file is immediately emptied (truncated to 0 bytes). All previous data is permanently deleted before any new data is written.
9. What common exceptions occur in File Handling?
FileNotFoundError (reading non-existent file), PermissionError (insufficient file permissions), and FileExistsError (using 'x' mode on an existing file).
10. How do you process a large 10GB file without crashing RAM?
Iterate line by line using a loop (for line in f:) or read in small fixed byte chunks using f.read(1024). Never load the entire file at once with read() or readlines().
6. 20 Lab Programs (With Code & Detailed Beginner Explanations)
Prog 01 Create a file and write a name
with open("my_name.txt", "w") as f:
f.write("Poorna Chandra\n")
print("File created and name saved successfully!")
- Line 1:
with open("my_name.txt", "w") as f:opens a file namedmy_name.txtin"w"(write) mode. If this file does not exist, Python automatically creates it. The file object is assigned to the variablef. - Line 2:
f.write("Poorna Chandra\n")writes the string into the file. The\ninserts a newline character at the end. - Line 3: Once execution leaves the
withblock, Python automatically closes the file to flush the buffer to disk.
Prog 02 Read a file and display its contents
try:
with open("my_name.txt", "r") as f:
content = f.read()
print("File Content:\n" + content)
except FileNotFoundError:
print("Error: The specified file does not exist.")
- Line 1:
try:starts a block to safely test the operation without crashing the program if the file is missing. - Line 2:
open("my_name.txt", "r")opens the file in read-only mode. - Line 3:
f.read()extracts the entire contents of the file and stores it into the variablecontent. - Line 5-6:
except FileNotFoundError:catches the error if the file name was mistyped or missing.
File Content:
Poorna Chandra
Prog 03 Append a new line to a file without overwriting
with open("my_name.txt", "a") as f:
f.write("Software Developer in Python\n")
print("New line appended successfully!")
- Line 1: Mode
"a"stands for Append. When opened, Python moves the cursor to the very end of the existing file rather than erasing what is already there. - Line 2:
f.write(...)appends the text after the existing lines.
Prog 04 Count the total number of lines in a file
line_count = 0
with open("my_name.txt", "r") as f:
for line in f:
line_count += 1
print(f"Total Lines: {line_count}")
- Line 1:
line_count = 0sets up a counter variable. - Line 4:
for line in f:is a memory-efficient loop that loads each line from disk one by one. - Line 5: Every iteration increments
line_countby 1.
Prog 05 Count the total number of words in a file
with open("my_name.txt", "r") as f:
text = f.read()
words = text.split()
print(f"Total Words: {len(words)}")
- Line 2:
text = f.read()reads the whole file into a single string variable. - Line 3:
text.split()breaks up the string by whitespace (spaces, tabs, newlines) into a list of individual words. - Line 5:
len(words)calculates the total number of elements in that list.
Prog 06 Copy content from one file into another file
with open("source.txt", "r") as src, open("destination.txt", "w") as dest:
data = src.read()
dest.write(data)
print("File copied successfully!")
- Line 1: Python allows opening multiple files in a single
withstatement separated by commas. We opensource.txtfor reading (src) anddestination.txtfor writing (dest). - Line 2-3:
src.read()grabs the content, anddest.write(data)writes that exact data into the new destination file.
Prog 07 Search for a specific word in a file
target_word = input("Enter word to search: ").strip()
found = False
with open("data.txt", "r") as f:
for line_number, line in enumerate(f, start=1):
if target_word.lower() in line.lower():
print(f"Found '{target_word}' at Line {line_number}: {line.strip()}")
found = True
if not found:
print(f"Word '{target_word}' was not found in the file.")
- Line 5:
enumerate(f, start=1)reads each line and provides a 1-based line index. - Line 6:
.lower()converts both the search query and the file line to lowercase so that searches are case-insensitive. - Line 8:
found = Truesets a flag to indicate the word exists in the file.
Enter word to search: Python
Found 'Python' at Line 1: Python Programming
Prog 08 Count all vowels in a file
vowels = "aeiouAEIOU"
vowel_count = 0
with open("data.txt", "r") as f:
text = f.read()
for char in text:
if char in vowels:
vowel_count += 1
print(f"Total Vowels Found: {vowel_count}")
- Line 1:
vowels = "aeiouAEIOU"contains all uppercase and lowercase vowels for comparison. - Line 6-7: The
forloop iterates through every single character in the file string. Theinoperator checks if the character is in our vowel lookup string.
Prog 09 Reverse the contents of a file
with open("source.txt", "r") as f:
data = f.read()
reversed_data = data[::-1]
with open("reversed.txt", "w") as f:
f.write(reversed_data)
print("Reversed file content created!")
- Line 4:
data[::-1]uses Python's extended slice syntax[start:stop:step]with a step of-1, which reverses the entire string backwards. - Line 6-7: We open a new file
reversed.txtand write the reversed string to it.
Prog 10 Merge two files into a third file
with open("file1.txt", "r") as f1, open("file2.txt", "r") as f2:
content1 = f1.read()
content2 = f2.read()
with open("merged.txt", "w") as f_out:
f_out.write(content1 + "\n" + content2)
print("Merged both files into merged.txt successfully!")
- Line 1-3: Opens two input files in read mode and stores their respective content in memory.
- Line 5-6: Concatenates both string blocks with a newline separator (
\n) and writes them out intomerged.txt.
Prog 11 Read a file line by line with formatted line numbers
with open("demo.txt", "r") as f:
for line_num, line in enumerate(f, start=1):
print(f"Line {line_num:02d}: {line.rstrip()}")
- Line 2:
enumerate(f, start=1)handles indexing lines starting at 1. - Line 3:
:02dformats the number with leading zeros (e.g., 01, 02).line.rstrip()removes trailing newline whitespace so lines do not print with blank gaps.
Line 01: Python
Line 02: Java
Line 03: C++
Prog 12 Store student records into a CSV file
students = [
["101", "Poorna", "92"],
["102", "Rahul", "85"],
["103", "Anjali", "96"]
]
with open("students.csv", "w") as f:
f.write("Roll,Name,Marks\n")
for row in students:
f.write(",".join(row) + "\n")
print("Student CSV file generated!")
- Line 8: We write the CSV table header string (
Roll,Name,Marks\n). - Line 10:
",".join(row)takes list elements like["101", "Poorna", "92"]and joins them with commas into a single string:"101,Poorna,92".
Prog 13 Read and parse student records from CSV into a table
with open("students.csv", "r") as f:
header = f.readline() # Skip column header line
print(f"{'ROLL':<10}{'NAME':<15}{'MARKS':<10}")
print("-" * 35)
for line in f:
roll, name, marks = line.strip().split(",")
print(f"{roll:<10}{name:<15}{marks:<10}")
- Line 2:
f.readline()advances past the first row of headers so it doesn't process with the data rows. - Line 6:
line.strip().split(",")removes newline endings and splits values at each comma into three variables (unpacking). - Line 7:
:<15formats text in aligned columns padded with spaces up to 15 characters wide.
ROLL NAME MARKS
-----------------------------------
101 Poorna 92
102 Rahul 85
103 Anjali 96
Prog 14 Rename a file safely using the os module
import os
old_file = "temp_data.txt"
new_file = "final_data.txt"
if os.path.exists(old_file):
os.rename(old_file, new_file)
print(f"Successfully renamed {old_file} to {new_file}")
else:
print(f"Cannot rename: {old_file} does not exist.")
- Line 6:
os.path.exists()checks if the target file is present to prevent throwing an unhandled exception. - Line 7:
os.rename(source, target)asks the operating system to update the filename.
Prog 15 Delete a file safely
import os
file_to_delete = "obsolete.txt"
if os.path.exists(file_to_delete):
os.remove(file_to_delete)
print(f"File {file_to_delete} was deleted.")
else:
print(f"File {file_to_delete} does not exist.")
- Line 6:
os.remove()permanently deletes the file from storage. Calling it on a missing file throws an error, which is why we wrap it inos.path.exists().
Prog 16 Copy a binary file (Image) using chunks
with open("input.png", "rb") as src, open("output_copy.png", "wb") as dest:
while True:
chunk = src.read(4096) # Read in 4 KB chunks
if not chunk:
break
dest.write(chunk)
print("Binary image copied successfully using buffers!")
- Line 1: Modes
"rb"and"wb"enable Binary mode for reading and writing raw byte streams. - Line 3:
src.read(4096)reads exactly 4,096 bytes (4 KB) at a time, keeping RAM consumption near zero regardless of how large the image or video is. - Line 4-5: When the end of the file is reached,
chunkevaluates to empty bytes (b''), triggeringbreakto end the loop.
Prog 17 Find the longest word in a text file
with open("data.txt", "r") as f:
words = f.read().split()
if words:
longest_word = max(words, key=len)
print(f"Longest Word: '{longest_word}' (Length: {len(longest_word)})")
else:
print("The file is empty.")
- Line 5:
max(words, key=len)iterates over the list of words, computes the string length of each word vialen, and returns the one with the maximum length.
Prog 18 Count frequency of each word in a file
frequency = {}
with open("data.txt", "r") as f:
for word in f.read().lower().split():
clean_word = word.strip(".,!?;:\"")
frequency[clean_word] = frequency.get(clean_word, 0) + 1
for word, count in sorted(frequency.items(), key=lambda x: x[1], reverse=True):
print(f"{word}: {count}")
- Line 5:
word.strip(".,!?;:\"")cleans punctuation marks attached to words. - Line 6:
frequency.get(clean_word, 0) + 1retrieves the current count of the word (defaulting to 0 if it hasn't been seen yet) and increments it by 1. - Line 8:
sorted()arranges the dictionary entries by count in descending order.
python: 4
file: 3
handling: 2
Prog 19 Remove all blank/empty lines from a file
with open("messy.txt", "r") as f:
clean_lines = [line for line in f if line.strip()]
with open("cleaned.txt", "w") as f:
f.writelines(clean_lines)
print("Cleaned file created with all blank lines removed!")
- Line 2: Uses a list comprehension.
if line.strip()checks if the line contains anything besides whitespace. Empty lines evaluate toFalseand are filtered out. - Line 5:
f.writelines(clean_lines)writes the filtered list of lines back to disk.
Prog 20 Capitalize the first letter of every word (Title Case)
with open("input.txt", "r") as f:
content = f.read()
title_content = content.title()
with open("title_cased.txt", "w") as f:
f.write(title_content)
print("Converted file content to Title Case successfully!")
- Line 4:
content.title()converts the first character of every word to uppercase and leaves all other letters in lowercase (e.g."hello world"→"Hello World"). - Line 7: Writes the transformed text to
title_cased.txt.
Summary Cheat Sheet
- Open / Close: Always use with open("name", "mode") as f:.
- Modes: r (read), w (overwrite), a (append), x (exclusive create), b (binary).
- File Pointer: tell() finds current cursor offset; seek(0) resets cursor back to line 1.
- OS Module: Use os.path.exists(), os.rename(), and os.remove() for file system tasks.
0 Comments