Category: python
Python File Handling
Published on 24 Jul 2026
Explanation
File handling is the process of creating, reading, writing, and modifying files stored on a computer. Python provides built-in functions
Code:
# Opening a file in read mode
file = open('sample.txt', 'r')
print('File Opened Successfully')
file.close()
print('File Closed')
Explanation
Python provides multiple methods for reading the contents of a file. The read() method reads the entire file as a
Code:
# Read entire file
file = open('sample.txt', 'r')
print(file.read())
file.close()
# Read line by line
file = open('sample.txt', 'r')
print(file.readline())
print(file.readline())
file.close()
# Read using loop
file = open('sample.txt', 'r')
for line in file:
print(line.strip())
file.close()
Explanation
Python allows writing new content to files using write mode ('w') and appending additional content using append mode ('a'). When
Code:
# Write to a file
file = open('students.txt', 'w')
file.write('John\n')
file.write('Alice\n')
file.write('David\n')
file.close()
# Append new data
file = open('students.txt', 'a')
file.write('Peter\n')
file.close()
print('Data Written Successfully')
Explanation
The with statement is the recommended way to work with files in Python. It automatically closes the file after the
Code:
# Reading using with
with open('sample.txt', 'r') as file:
content = file.read()
print(content)
# Writing using with
with open('output.txt', 'w') as file:
file.write('Welcome to Python File Handling')
print('File operations completed successfully.')
Explanation
File handling is frequently used in real-world applications to store and retrieve persistent data. Examples include employee records, customer details,
Code:
students = [
'101,John,85',
'102,Alice,90',
'103,David,78'
]
# Save records
with open('students.txt', 'w') as file:
for student in students:
file.write(student + '\n')
# Read records
print('Student Records')
print('---------------')
with open('students.txt', 'r') as file:
for line in file:
print(line.strip())