Python’s os.path module can be used for dealing with file paths/pathnames. Using functions inside this module, you can get information about current working path, directory name and also using this os.path module file system can be traversed to look for some specific file. (Quite Confusing!!🤷🏻 🤷🏻)
Just note that almost all of functions in os.path module take in a string/bytes object as parameter and return path/file name. For example – os.path.split(path) function takes in path parameter(string/bytes object) and return (directory name, filename) object.
Let me explain this for you.
Table of Contents
Functions in os.path Module – Table
Function Name | Description |
---|---|
os.path.adbspath(path) | Returns a normalized absolutized version of pathname |
os.path.basename(path) | Returns base name of a pathname |
os.path.commonpath(paths) 👉🏻 More than one path as a parameter | Returns longest common sub-path of each pathname passed as parameter |
os.path.exists(path) | Returns True if path refers to an existing path or an open file descriptor |
os.path.getatime(path) | Return time of last access of path |
os.path.getmtime(path) | Return time of last modification of path |
os.path.getctime(path) | Return the system’s ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path |
os.path.getsize(path) | Returns size of path(in bytes) |
os.path.isabs(path) | Returns True if path is an absolute pathname, False otherwise |
os.path.isfile(path) | Return True is path is an existing regular file |
os.path.isdir(path) | Returns True if path is an existing directory, otherwise returns false |
os.path.islink(path) | Returns True if path refers to an existing directory entry that is a symbol link |
os.path.ismount(path) | Return True if path is a mount point – a point in a file system where a different file system has been mounted |
os.path.join(path, *paths) | Joins one or more path componenets intelligently |
os.path.normcase(path) | Normalize case of pathname. On Windows convert all characters in pathname to lowercase and forward slashes to backward slashes. On all other operating systems return path unchanged |
os.path.normpath(path) | Normalize a pathname by collapsing all redundant separators and up-level references so that A//B, A/B/, A/./B, A/foo/../B will become just A/B |
os.path.realpath(path) | Return canonical path of specified filename and eliminate any symbolic links encountered in path |
os.path.relpath(path, start=os.curdir) | Return canonical path of specified filename |
os.path.samefile(path1, path2) | Return True if both pathnames refer to same file or directory |
os.path.sameopenfile(fp1, fp2) | Return True if file descriptors fp1 and fp2 refer to same file |
os.path.samestat(stat1, stat2) | Return True if stat tuples stat1 and stat2 refer to same file |
os.path.split(path) | Split pathname into a pair (head, tail) where tail is last pathname component and head is everything leading up to that |
os.path.splitdrive(path) | Split pathname into a pair (drive, tail) where drive is either a mount point or empty string. On systems which do not use drive specifications, drive will always be empty string |
os.path.splittext(path) | Split pathname path into a pair (root, ext) such that root + ext == path and ext is empty or begins with a period and contains at most one period |
os.path.supports_unicode_filenames | True if arbitrary unicode strings can be used as file names |
Using os.path module to Handle Filenames
Let’s you creating a folder Testing on Desktop of your laptop then create a file named somefile inside Testing folder.
import os
filename = "desktop/testing/somefile"
print("using", os.name, "...")
print("split", "=>", os.path.split(filename))
print("splitext", "=>", os.path.splitext(filename))
print("dirname", "=>", os.path.dirname(filename))
print("basename", "=>", os.path.basename(filename))
print("join", "=>", os.path.join(os.path.dirname(filename),
os.path.basename(filename)))
print("join", "=>", os.path.isdir(filename))
This code when run will output something like following –

Now you can clearly get an idea about how os.path module functions – split(), splittext(), dirname(), basename(), isdir() works.
Using os.path Module for Inserting Username into a Filename
import os
print os.path.expanduser("~/.pythonrc")
Using os.path module for Inserting Variables into a Filename
import os
os.environ["USER"] = "user"
print os.path.expandvars("/home/$USER/config")
# Prints out => /home/user/config
print os.path.expandvars("$USER/folders")
# Prints out => user/folders
Python loop through files in directory recursively using os.path Module
import os
def callback(arg, directory, files):
for file in files:
print os.path.join(directory, file), repr(arg)
os.path.walk(".", callback, "secret message")
# Above Code Prints out
./aifc-example-1.py 'secret message'
./anydbm-example-1.py 'secret message'
./array-example-1.py 'secret message'
...
./samples 'secret message'
./samples/sample.jpg 'secret message'
./samples/sample.txt 'secret message'
./samples/sample.zip 'secret message'
./samples/articles 'secret message'
./samples/articles/article-1.txt 'secret message'
./samples/articles/article-2.txt 'secret message'
...
Traversing Filesystem using os.path module function listdir()
import os
def index(directory):
# like os.listdir, but traverses directory trees
stack = [directory]
files = []
while stack:
directory = stack.pop()
for file in os.listdir(directory):
fullname = os.path.join(directory, file)
files.append(fullname)
if os.path.isdir(fullname) and not os.path.islink(fullname):
stack.append(fullname)
return files
for file in index("."):
print file
# Above Code Prints out
.\aifc-example-1.py
.\anydbm-example-1.py
.\array-example-1.py
...
Using Directory Walker to Traverse Filesystem
import os
class DirectoryWalker:
# a forward iterator that traverses a directory tree
def _ _init_ _(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def _ _getitem_ _(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
return fullname
for file in DirectoryWalker("."):
print file
# Above Code Prints out
.\aifc-example-1.py
.\anydbm-example-1.py
.\array-example-1.py
...
Using DirectoryStatWalker for Traversing FileSystem
import os, stat
class DirectoryStatWalker:
# a forward iterator that traverses a directory tree, and
# returns the filename and additional file information
def _ _init_ _(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def _ _getitem_ _(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
st = os.stat(fullname)
mode = st[stat.ST_MODE]
if stat.S_ISDIR(mode) and not stat.S_ISLNK(mode):
self.stack.append(fullname)
return fullname, st
for file, st in DirectoryStatWalker("."):
print file, st[stat.ST_SIZE]
# Above code prints out
.\aifc-example-1.py 336
.\anydbm-example-1.py 244
.\array-example-1.py 526
No Comments
Leave a comment Cancel