๐ Mastering File Handling in Python: Read, Write, and Delete Files Like a Pro


1. ๐ Mastering File Reading in Python: read()
, readline()
, and readlines()
Explained
Python offers three powerful methods to read content from a file: read()
, readline()
, and readlines()
. Each has specific use cases.
โ
read()
Purpose: Reads the entire content of the file as a single string.
Use case: Best for small files when you want all data at once.
with open("sample.txt", "r") as file: content = file.read() print(content)
๐ค Output:
Hello, this is line 1 This is line 2 And this is line 3
โ
readline()
Purpose: Reads one line at a time.
Use case: Useful for reading large files line by line to save memory.
with open("sample.txt", "r") as file: line1 = file.readline() line2 = file.readline() print(line1.strip()) print(line2.strip())
๐ค Output:
Hello, this is line 1 This is line 2
โ
readlines()
Purpose: Reads all lines into a list where each line is an item.
Use case: Convenient when you want to loop through lines.
with open("sample.txt", "r") as file: lines = file.readlines() for line in lines: print(line.strip())
๐ค Output:
Hello, this is line 1 This is line 2 And this is line 3
2. ๐ Writing and Managing Files in Python: Creating, Writing, and Closing Files
Writing to files in Python is just as simple as reading. You use modes like 'w'
(write) or 'a'
(append).
โ๏ธ Create & Write a New File
with open("output.txt", "w") as file:
file.write("This is a new file.\n")
file.write("It contains some text.")
'w'
mode will create the file if it doesn't exist, or overwrite it if it does.
๐ output.txt content:
This is a new file.
It contains some text.
โ Append to a File
with open("output.txt", "a") as file:
file.write("\nThis is an appended line.")
๐ Updated output.txt:
This is a new file.
It contains some text.
This is an appended line.
โ Closing Files
When using with open(...)
, Python automatically closes the file. If not, always remember to close manually:
file = open("example.txt", "w")
file.write("Hello world!")
file.close()
โ
Best Practice: Always prefer with
block to handle file closing safely.
3. ๐๏ธ How to Delete Files Using Pythonโs os
Module: A Practical Guide
Sometimes, you need to remove files after processing. Pythonโs os
module helps you safely do this.
๐ง Step-by-Step Deletion
import os
file_path = "output.txt"
# Check if file exists before deleting
if os.path.exists(file_path):
os.remove(file_path)
print("File deleted successfully.")
else:
print("File does not exist.")
๐ This avoids errors like:
FileNotFoundError: [Errno 2] No such file or directory
โ ๏ธ Important Tips
Use
os.remove()
only for files, not folders.To delete directories, use
os.rmdir()
(for empty folders) orshutil.rmtree()
(for non-empty folders).
import shutil
# To delete a folder and its contents
shutil.rmtree("example_folder")
๐ Wrapping Up
Mastering file handling in Python opens up a lot of possibilitiesโfrom simple automation to full-fledged data processing apps. Here's a quick summary:
Action | Method | Notes |
Read entire file | read() | Loads all content at once |
Read line by line | readline() | Reads one line per call |
Read lines as list | readlines() | Returns list of all lines |
Write to file | write() | Overwrites or appends |
Delete file | os.remove() | Check with os.path.exists() / |
Subscribe to my newsletter
Read articles from Jugal kishore directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
