7 Tips to Play With File Names, Directory Names, and Paths Using Python OS.path Module

Python’s OS.path module have a lots of commands/methods that are greatly useful for all things files/directories/paths. Here is seven tips for playing with files, directories, and paths using using Python os.path.

How To Check If a “Name” is a Directory?

To make sure if a name is directory or not, one can use “os.path.dir” to check it. “os.path.dir(name)” will return “True”, if it is a directory and “False” if it is not.

>>> os.path.isdir("cmdlineTips")
>>> os.path.isdir("pythonTips.pdf")

How To Check If a “Name” is a File?

Similarly, one can use “os.path.isfile(name)” to check if the name is a file or not. Note that “os.path.isfile” will return false, if there is no file with the name.

>>> os.path.isfile("pythonTips.pdf")
>>> os.path.isfile("cmdlineTips")
>>> os.path.isfile("pythonTip.pdf")

How To Check If a File Exists?

To check if a file exists in a directory, use “os.path.exists”.

>>> os.path.exists("pythonTip.pdf")
>>> os.path.exists("pythonTips.pdf")

How To Get File Size?

To get the size of a file, use “os.path.getsize”. It will give file size in bytes.

>>> os.path.getsize("pythonTips.pdf")

How To Split Path and Get File/Directory Name?

There are numerous ways to split a path and get the directory/file name at the path and get the base name from the path.

The Python command “os.path.split(path2File)” splits the path in to head and tail, where tail is the last part in the path. Python documents says that

The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only).

For example

>>> path2File = "/Users/cmdlinetips/pythonTips.pdf"
>>> os.path.split(path2File)
('/Users/cmdlinetips', 'pythonTips.pdf')

Another way to get the file name (or directory name) from a path is to use “os.base.basename”. Here is an example

>>> os.path.basename(path2File)

How To Get the Extension of a File Name from a Path?

If you just want to get the extension of a file from a path, use “os.path.splitext” and the second element from the tuple is the extension of file name.

>>> os.path.splitext(path2File)
('/Users/cmdlinetips/pythonTips', '.pdf')

If your path is a directory, “os.path.splitext” will have an empty string at the second element at the output tuple.

path2File = "/Users/cmdlinetips/pythonTips"
>>> os.path.splitext(path2File)
('/Users/cmdlinetips/pythonTips', '')


>>> os.path.dirname(path2File)

How to Get The Complete Path to a File in Current Directory?

The Python command “os.path.abspath” gives the full/complete path to a file in current directory.

>>> os.path.abspath("pythonTips.pdf")
>>> os.path.abspath("")