File and Directory Handling in Python
Variables, lists, and dictionaries store data in RAM (Volatile Memory) — as soon as the program terminates, all data is lost. To store data permanently on the hard disk (Non-Volatile Memory), we use Files.
Types of Files in Python:
- Text Files (
.txt,.csv,.py): Store data as human-readable characters where each line ends with a newline character (\n). - Binary Files (
.jpg,.mp3,.pdf,.dat): Store data in raw bytes (0s and1s) that can only be read by specific programs.
f = open("data.txt", "r")f.read() or f.write()f.close()1. Opening a File & File Access Modes
In Python, we use the built-in open(filename, mode) function to open a file.
| Mode | Name | Description | If File Doesn’t Exist |
|---|---|---|---|
'r' |
Read (Default) | Opens file for reading only (cursor at start) | Raises FileNotFoundError |
'w' |
Write | Opens file for writing. Overwrites existing content! | Creates a new file |
'a' |
Append | Opens file for adding new data at the end without deleting old data | Creates a new file |
'x' |
Exclusive Create | Creates a new file; fails if file already exists | Creates a new file |
'r+' |
Read + Write | Opens existing file for both reading and writing | Raises FileNotFoundError |
'w+' |
Write + Read | Overwrites existing file for writing and reading | Creates a new file |
'rb' / 'wb' |
Binary Modes | Reads or writes in raw binary format (images/audio) | 'wb' creates new file |
2. Writing Data to a File (write() and writelines())
f.write(string): Writes a single string to the file.f.writelines(list_of_strings): Writes multiple strings from a list to the file.
# Writing to a file ('w' mode creates or overwrites the file)
f = open("notes.txt", "w")
f.write("Welcome to Python File Handling!\n")
f.write("This is Unit 3 of BCA Syllabus.\n")
f.close()
# Appending new data to the end of the file ('a' mode)
f = open("notes.txt", "a")
f.write("Appending a 3rd line without deleting previous lines.\n")
f.close()
3. Reading Data from a File (read(), readline(), readlines())
| Method | What It Returns |
|---|---|
f.read() |
Reads the entire file and returns it as a single string (f.read(n) reads n characters) |
f.readline() |
Reads only one single line from the file at a time |
f.readlines() |
Reads all lines and returns them as a List of strings |
f = open("notes.txt", "r")
# Read entire file content
content = f.read()
print(content)
f.close()
Best Practice: The with open(...) Statement (Context Manager)
When you open a file using the with keyword, Python automatically closes the file as soon as the block finishes (even if an error occurs!). You never need to write f.close().
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
# File is automatically closed here!
4. Moving the File Cursor: tell() and seek()
When reading or writing a file, Python maintains an internal File Pointer (Cursor) that tracks your current byte position.
f.tell(): Returns the current position (in bytes) of the file pointer from the beginning of the file.f.seek(offset): Moves the file pointer to a specific byte position (f.seek(0)resets the cursor back to the very beginning of the file).
with open("notes.txt", "r") as f:
print("Initial cursor at:", f.tell()) # Output: 0
print(f.read(7)) # Output: Welcome
print("Cursor after reading 7 chars:", f.tell()) # Output: 7
f.seek(0) # Rewind cursor back to start of file!
print("Cursor reset to:", f.tell()) # Output: 0
5. Directory (Folder) Handling in Python
Python uses the os and shutil modules to create, inspect, rename, and delete directories (folders):
import os
# 1. Get Current Working Directory
print("Current Directory:", os.getcwd())
# 2. Create a new directory
os.mkdir("Project_Files")
# 3. Rename a directory or file
os.rename("Project_Files", "BCA_Project_Files")
# 4. List all files and subdirectories inside current folder
print("Contents:", os.listdir("."))
# 5. Remove an empty directory
os.rmdir("BCA_Project_Files")
(Note: To delete a non-empty directory along with all its files, use shutil.rmtree("folder_name") from the shutil module).