-
Hajipur, Bihar, 844101
In Python, file handling allows you to store, read, update, and delete data in files. Files are essential for data persistence, enabling programs to save information that can be used later. Python provides built-in functions and methods to handle files efficiently.
This tutorial will cover opening and closing files, reading, writing, deleting, file modes, and practical examples, giving you the skills to work with files in real-world applications.
File handling is the process of creating, reading, writing, and managing files in a program. Python supports multiple file types such as text files (.txt), CSV files (.csv), JSON files (.json), and binary files (.bin). By mastering file handling, you can:
Save program output to a file
Read data from existing files
Process large datasets efficiently
Maintain logs and persistent records
Python uses the built-in open() function to open a file. The general syntax is:
file_object = open("filename", "mode")
filename – Name of the file
mode – Mode in which to open the file (read, write, append, etc.)
After performing file operations, it’s important to close the file using close():
file = open("sample.txt", "r")
# Perform operations
file.close()
Closing files ensures resources are freed and data is properly saved.
When opening a file, you must specify the mode. Python provides several modes:
| Mode | Description |
|---|---|
r |
Read (default). Opens file for reading. Error if file does not exist. |
w |
Write. Creates a new file or overwrites an existing file. |
a |
Append. Adds content to the end of the file if it exists. |
x |
Create. Creates a new file, returns error if file exists. |
rb |
Read binary. For binary files like images. |
wb |
Write binary. For writing binary files. |
ab |
Append binary. For adding to binary files. |
Choosing the correct mode is crucial for avoiding data loss or errors.
Python provides multiple methods to read file content:
read()Reads the entire file:
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()
readline()Reads one line at a time:
file = open("sample.txt", "r")
line = file.readline()
print(line)
file.close()
readlines()Reads all lines into a list:
file = open("sample.txt", "r")
lines = file.readlines()
print(lines)
file.close()
You can write data to a file using write() or writelines():
file = open("example.txt", "w")
file.write("Python File Handling Tutorial\n")
file.write("This is a new file.\n")
file.close()
write() writes a single string.
writelines() writes a list of strings to the file:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open("example.txt", "w")
file.writelines(lines)
file.close()
Note: Using mode w will overwrite existing files.
Use mode a to add data to the end of a file without deleting existing content:
file = open("example.txt", "a")
file.write("This line will be added.\n")
file.close()
Appending is helpful for logs, records, or sequential data storage.
Python’s os module allows you to delete files:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted successfully.")
else:
print("File not found.")
Deleting ensures unnecessary or temporary files do not occupy space.
with Statement (Context Manager)Using with automatically handles opening and closing files, making the code cleaner:
with open("sample.txt", "r") as file:
content = file.read()
print(content)
# No need to call file.close()
Context managers prevent resource leaks and are considered best practice in Python file handling.
Read and print a file:
with open("sample.txt", "r") as file:
print(file.read())
Write multiple lines to a file:
lines = ["Python\n", "File Handling\n", "Tutorial\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
Append text to a file:
with open("example.txt", "a") as file:
file.write("Additional line.\n")
Read file line by line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Delete a file if it exists:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("Deleted successfully.")
Check file existence before reading:
import os
if os.path.isfile("sample.txt"):
with open("sample.txt", "r") as file:
print(file.read())
Write a list of names to a file:
names = ["Ananya\n", "Meera\n", "Riya\n"]
with open("students.txt", "w") as file:
file.writelines(names)
Count number of lines in a file:
with open("students.txt", "r") as file:
lines = file.readlines()
print("Number of lines:", len(lines))
Read first 10 characters of a file:
with open("students.txt", "r") as file:
print(file.read(10))
Append multiple lines safely:
new_lines = ["Sana\n", "Muskan\n"]
with open("students.txt", "a") as file:
file.writelines(new_lines)
Python file handling allows programs to interact with files for reading, writing, appending, and deleting data. By mastering file handling, you can:
Persist program data for future use
Manage large datasets efficiently
Create logs, reports, and backups
Handle text and binary files
Key points to remember:
Always close files or use with for automatic management
Choose the correct file mode to avoid overwriting or errors
Use os.remove() to safely delete files
Use file methods like read(), readline(), writelines() for flexible operations
File handling is essential for real-world Python applications, including data analysis, automation, and application development.
Q1. Write a Python program to create a file named data.txt and write your name in it.
Q2. Write a Python program to append a new line to data.txt using append ("a") mode.
Q3. Write a Python program to read and print all contents from data.txt.
Q4. Write a Python program to read only the first 10 characters of a file using read(10).
Q5. Write a Python program to read all lines one by one using the readline() method in a loop.
Q6. Write a Python program to use with open() to read a file safely, ensuring it auto-closes.
Q7. Write a Python program to check if data.txt exists before opening it using os.path.exists().
Q8. Write a Python program to delete a file named test.txt using the os.remove() function.
Q9. Write a Python program to create a file using "x" mode, which throws an error if the file already exists.
Q10. Write a Python program to print the file size of data.txt if it exists, using os.path.getsize().