


Khusboo Tayal
File handling in Python allows you to work with external files stored on your computer. Whether you're reading from or writing to a file, Python provides a simple and powerful way to handle files using built-in functions like open(), read(), write(), and close().
To work with a file, you first need to open it using the open() function:
file = open("example.txt", "r") # 'r' means read mode
| Mode | Description |
|---|---|
| 'r' | Read (default) |
| 'w' | Write (overwrites file) |
| 'a' | Append (adds to the end) |
| 'x' | Create file, error if exists |
| 'b' | Binary mode |
| 't' | Text mode (default) |
You can read file content using methods like read(), readline(), or readlines():
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()file = open("example.txt", "r")
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)
file.close()file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
print(line.strip())
file.close()Use write() or writelines() to write content:
file = open("example.txt", "w")
file.write("Hello, Python File Handling!")
file.close()This will overwrite the content if the file already exists.
Use append mode 'a' to add content without deleting existing data:
file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()Python provides a better way to handle files using with, which automatically closes the file:
with open("example.txt", "r") as file:
content = file.read()
print(content)
This is the recommended way to handle files as it ensures proper resource management.
Use writelines() to write a list of strings:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
file.writelines(lines)Use the os module to check if a file exists before opening:
import os
if os.path.exists("example.txt"):
print("File exists.")
else:
print("File not found.")You can delete files using the os.remove() method:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")Use try...except to handle such errors gracefully.
File handling is a critical skill in Python programming. It enables you to build interactive and real-world applications that read from or write to files efficiently. Remember to always close your files or use the with statement for better resource management.
Q1: What’s the difference between 'w' and 'a' mode?
'w' overwrites the file, while 'a' appends to it.
Q2: Can I open multiple files at once?
Yes, use multiple with statements or context managers.
Q3: How do I read a file line by line?
Use a loop with readlines() or iterate directly:
with open("file.txt") as f:
for line in f:
print(line.strip())Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythonfilehandling #pythonreadfile #pythonwritefile #fileoperations #learnpython #pythontutorial #pythonbeginners #fileio #pythonbasics