Python Lesson 14: Basic File Handling
PYTHON
AllComputerss
4/18/20261 min read


Working with files is a common task in programming. Python makes it easy to read from and write to files, allowing you to store data persistently and process external information.
Opening Files
You can open a file using the built-in open() function. It requires the filename and mode:
r → Read (default)
w → Write (creates/overwrites file)
a → Append (adds to the end of file)
b → Binary mode
# Opening a file in read mode
file = open("example.txt", "r")
print(file.read())
file.close()
Writing to Files
You can create or overwrite files using write mode:
# Writing to a file
file = open("example.txt", "w")
file.write("Hello, Python file handling!")
file.close()
Appending to Files
Appending adds new content without deleting existing data:
# Appending to a file
file = open("example.txt", "a")
file.write("\nThis line is appended.")
file.close()
Using with Statement
The with statement automatically closes the file after use, making it safer and cleaner:
# Reading a file safely
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading Files Line by Line
You can loop through a file to process it line by line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Conclusion
File handling in Python is straightforward and powerful. By mastering reading, writing, and appending files, you can build applications that store and process data efficiently. In the next lessons, you’ll explore more advanced topics like working with CSV and JSON files.
© 2026 AllComputerss. All rights reserved.