Files & Directories in Python
Learn how to create, check, rename, move and delete files and directories using Python.
What are Files and Directories?
A file stores data such as text, images, documents or other information.
A directory, also called a folder, is used to organize files and other directories.
Example 👀🌍
Imagine a training institute project.
Students Folder
Contains student information files.
Reports Folder
Contains generated reports.
Fees File
Stores fee-related information.
Files & Directories Diagram
Main Project Folder
Contains files and subdirectories.
Directory
students/
Directory
reports/
File
config.txt
File System Operations
Create, read, rename, move, list and delete.
The os Module
Python provides the os module for
interacting with the operating system.
import os
The os module provides functions for
working with files, directories and paths.
Get Current Working Directory
The os.getcwd() function returns the
current working directory.
import os
current_directory = os.getcwd()
print(current_directory)
This helps us understand where the Python program is currently working.
List Files and Directories
The os.listdir() function returns the
names of files and directories.
import os
items = os.listdir()
print(items)
The result contains the items found in the specified directory.
List a Specific Directory
import os
items = os.listdir("students")
print(items)
This lists the contents of the students
directory.
Check Whether a Path Exists
The os.path.exists() function checks
whether a file or directory exists.
import os
if os.path.exists("students.txt"):
print("File or directory exists")
else:
print("Path does not exist")
Check Whether a Path is a File
Use os.path.isfile() to check whether
a path points to a file.
import os
if os.path.isfile("students.txt"):
print("This is a file")
else:
print("This is not a file")
Check Whether a Path is a Directory
Use os.path.isdir() to check whether
a path points to a directory.
import os
if os.path.isdir("students"):
print("This is a directory")
else:
print("This is not a directory")
Create a Directory
The os.mkdir() function creates
a new directory.
import os
os.mkdir("students")
A new directory named students
is created.
Create Nested Directories
The os.makedirs() function can create
multiple directories in a path.
import os
os.makedirs("training/python/beginners")
The required directory structure is created.
Rename a File or Directory
The os.rename() function can rename
a file or directory.
import os
os.rename(
"students.txt",
"student_list.txt"
)
The original name is changed to the new name.
Delete a File
The os.remove() function deletes
a file.
import os
os.remove("student_list.txt")
Delete an Empty Directory
The os.rmdir() function removes
an empty directory.
import os
os.rmdir("students")
The directory must be empty before using
os.rmdir().
The shutil Module
The shutil module provides higher-level
operations for copying, moving and deleting files
and directories.
import shutil
Copy a File
Use shutil.copy() to copy a file.
import shutil
shutil.copy(
"students.txt",
"students_backup.txt"
)
A copy of the file is created.
Copy a Directory
The shutil.copytree() function can
copy a directory and its contents.
import shutil
shutil.copytree(
"students",
"students_backup"
)
The directory and its contents are copied.
Move a File or Directory
Use shutil.move() to move a file
or directory to another location.
import shutil
shutil.move(
"students.txt",
"reports/students.txt"
)
The file is moved to the specified destination.
Using pathlib
Python also provides the pathlib module,
which offers an object-oriented way to work with paths.
from pathlib import Path
path = Path("students.txt")
print(path.exists())
pathlib is useful for writing clear
and readable file-system code.
Path Information
from pathlib import Path
path = Path("reports/students.txt")
print(path.name)
print(path.parent)
print(path.suffix)
These properties provide information about the path.
Creating a Directory with pathlib
from pathlib import Path
folder = Path("reports")
folder.mkdir(exist_ok=True)
The exist_ok=True option prevents an
error when the directory already exists.
List Directory Contents with pathlib
from pathlib import Path
folder = Path("reports")
for item in folder.iterdir():
print(item)
This loops through files and directories inside the selected folder.
Joining Paths
pathlib can be used to build paths
without manually joining strings.
from pathlib import Path
folder = Path("reports")
file_path = folder / "students.txt"
print(file_path)
os.path vs pathlib
| os.path | pathlib |
|---|---|
| Traditional path-handling approach. | Object-oriented path handling. |
Uses functions such as
os.path.exists().
|
Uses Path objects. |
| Widely used in existing Python code. | Provides a modern, readable path API. |
Practical Project Structure
myproject/
|
|-- students/
| |
| |-- student1.txt
| |-- student2.txt
|
|-- reports/
| |
| |-- report1.txt
|
|-- main.py
Python can create, list, move, copy and remove these files and directories programmatically.
Common File and Directory Operations
| Operation | Python Tool |
|---|---|
| Get current directory | os.getcwd() |
| List directory | os.listdir() |
| Check path | os.path.exists() |
| Check file | os.path.isfile() |
| Check directory | os.path.isdir() |
| Create directory | os.mkdir() |
| Create nested directories | os.makedirs() |
| Rename | os.rename() |
| Delete file | os.remove() |
| Copy | shutil.copy() |
| Move | shutil.move() |
Best Practices
- Use clear and meaningful file and directory names.
- Check whether a path exists before performing operations when appropriate.
- Be careful while deleting files and directories.
-
Use
pathlibwhen it makes path operations clearer. - Handle possible operating-system errors.
Common Mistakes
- Using an incorrect path.
-
Trying to delete a directory that is not empty
using
os.rmdir(). - Trying to open a file that does not exist.
- Accidentally deleting important files.
- Confusing a file path with a directory path.
Practice Programs
- Display the current working directory.
- List all files and folders in the current directory.
-
Create a directory named
students. - Check whether a file exists.
- Rename a file using Python.
-
Copy a file using
shutil. - Move a file into another directory.
-
Create a directory using
pathlib.
Summary
Python provides several tools for working with files
and directories. The os module is useful
for common operating-system operations,
shutil provides higher-level copy and
move operations, and pathlib provides
an object-oriented way to work with paths. Using these
tools, Python programs can create, check, list, rename,
copy, move and delete files and directories.