Programming, Python
Python Files and Directories Explained
File handling is a core part of Python programming. Every time you read a config file, write a log, or scan a folder for uploads, you are using the concepts covered here: what files and directories are, how paths work, and which built-in modules let you list and traverse the filesystem. This article walks through those concepts with working code examples. Need help with a file I/O assignment? Python Assignment Help is available from developers who specialize in this language.

What is a File?
A file is a collection of related information stored together on a computer. It can hold text, images, audio, video, or any other data. Operations on files include creating, opening, reading, writing, and closing them.
In Python, files are opened with the built-in open() function. It takes two arguments: the filename and the access mode. The 4 most common modes are:
'r'- read mode'w'- write mode'a'- append mode'x'- exclusive creation mode (fails if the file already exists)
Read mode lets you read the contents but not modify them. Write mode overwrites or creates the file. Append mode adds content at the end of an existing file. Exclusive creation mode creates a new file only when no file with that name exists.
Opening a file in read mode looks like this:
file = open('example.txt', 'r')
What is a Directory?
A directory is a container for files. Directories give your filesystem a hierarchical structure. Each directory holds files and other directories, which can be further organized into subdirectories. A Music folder, for example, might contain subfolders for each genre, each holding individual audio files. Graphical operating systems display directories as folders.
How Files and Directories Connect
In a filesystem, files and directories connect through paths. A path is a string that specifies the location of a file or directory.
There are 2 types of paths: absolute and relative.
An absolute path gives the full location from the root directory. On Windows that looks like C:\Users\UserName\Documents\myfile.txt. On Linux and macOS it looks like /home/user/myfile.txt. Absolute paths are unambiguous regardless of where your script runs.
A relative path specifies the location from the current working directory. If your working directory is C:\Users\UserName\Documents, then a relative path to a file in that same folder is simply myfile.txt. The notation ../../myfile.txt means the file lives two directories above the current one. Relative paths make code more portable because they do not depend on a fixed directory structure.
Listing Files in a Directory
Python provides 3 modules for accessing and listing files: the os module, the pathlib module, and the glob module. Each offers different functions and suits different use cases.
The os Module
The os module is part of Python's standard library. It provides functions for interacting with the operating system, including 3 main ways to list directory contents.
os.listdir() returns a list of all entries (files and subdirectories) in the specified path:
import os
path = "/path/to/my_dir"
file_list = os.listdir(path)
print(file_list)
os.walk() traverses a directory tree recursively and yields a tuple of (root, dirs, files) for each directory it visits. Use it when you need every file at every depth:
import os
path = "/path/to/my_dir"
for root, dirs, files in os.walk(path):
for file in files:
print(os.path.join(root, file))
os.path.join() combines the root directory with each filename to produce a correct absolute path, regardless of operating system.
os.scandir() returns an iterator of DirEntry objects rather than plain strings, giving you access to metadata like file type without extra stat() calls. It is the preferred choice when you need to filter by type:
import os
path = "/path/to/my_dir"
with os.scandir(path) as entries:
for entry in entries:
if entry.is_file():
print(entry.name)
The with block ensures the directory handle closes when the loop finishes. The entry.is_file() check skips subdirectories and returns only files.
The glob Module
The glob module matches filenames against shell-style patterns. It is the right tool when you need only files with a specific extension or naming convention, rather than everything in a folder.
glob.glob() returns a list of all matching filenames at once. glob.iglob() returns an iterator that yields filenames one by one. The iterator form is more memory-efficient when a pattern matches thousands of files.
import glob
path = "/path/directory/"
pattern = "*.txt"
# Using glob() - returns a list
files = glob.glob(path + pattern)
print("Matching files:", files)
# Using iglob() - returns an iterator
iterator = glob.iglob(path + pattern)
print("Matching files (using iterator):")
for file in iterator:
print(file)
Both methods accept wildcards: * matches any sequence of characters, and ? matches any single character. Use glob() when you need the full list in memory; use iglob() when processing files one at a time.
Wrapping Up
Python's os and glob modules cover the most common file-system tasks: reading a specific file, walking a directory tree, and filtering by filename pattern. The pathlib module (available since Python 3.4) offers an object-oriented alternative worth exploring once you are comfortable with these basics.
If you are working through a file I/O assignment and hitting issues with paths or directory traversal, the developers at GeeksProgramming can review your code. You may also find these related posts useful: Filtering Lists in Python covers data manipulation techniques that pair well with file reading, and Efficient Algorithms in Python shows how to keep processing fast once you have data loaded from disk.
Related articles
- Programming
How to Become a Python Developer
A step-by-step roadmap covering core Python concepts, libraries, frameworks, databases, testing, DevOps, and interview prep for aspiring Python developers.
Oct 26, 2024
- Case Study
Autograder Fixed in Under 24 Hours: 100/100
How our networking expert diagnosed a broken distance vector routing submission, fixed the output formatting bug, and delivered a 100/100 autograder score before the deadline.
Sep 2, 2025
- Programming
Can You Get Caught Using Someone Else's Code?
Yes, you can get caught. MOSS, JPlag, and Codequiry detect copied code even after renaming variables or restructuring. Here is what actually happens if you are.
Jul 17, 2025


