Path. A file system stores information about its files. With the os.path module in Python, we access this information. Many methods are available here.
We detect whether a file is present with path.exists. We read dates, get sizes and list file names. We split and join paths. We can even find a common prefix of 2 paths.
Exists. This example uses the path.exists method. We pass a string containing a file's location on the system disk. If the file does not exist, path.exists returns false.
Tip This method can be used to avoid IOErrors that occur when a program tries to open a file that does not exist.
from os import path
# See if this file exists.# ... Write a custom message based on the result.
if path.exists("/enable1.txt"):
print("File exists")
else:
print("File not found, sorry")File exists
Getsize. How many bytes are in a file? There are several ways to get this information. We could read in the file and count the bytes. But the path.getsize() method is simpler.
Detail The path.getsize method returns a numeric figure. This is the byte count of the target file.
Note The returned value is in bytes, not megabytes. To change the number to megabytes, we would need to divide it.
from os import path
# Get size of this text file.
size = path.getsize("/enable1.txt")
# Display the size in bytes.
print(size)1916146
Commonprefix. The path module includes a method called commonprefix. This method receives a list of paths. It scans these strings and returns the longest shared common prefix.
Warning Commonprefix does no validation—the prefix may not be a valid path. Be careful with invalid data.
Here We create an empty list and then append three paths two it. Then, the commonprefix method returns the longest prefix.
Note It returns the name of the enclosing folder of all the files. It omits the nested folder.
from os import path
# Add paths to a list.
paths = []
paths.append("C:\directory\name")
paths.append("C:\directory\image")
paths.append("C:\directory\folder\index")
# Get common prefix of the paths.
prefix = path.commonprefix(paths)
print(prefix)C:\directory
List files. How can we get a list of the files in a directory? The os.listdir method is helpful here. It receives a directory path. It returns a list of the file names in the directory.
Tip There are just file names, not paths. To open these files, we must combine the file name with the path.
import os
# Get all files in this directory.
list = os.listdir("C:\\programs\\")
print(list)['file.php', 'file.pl', 'file.py', 'file.rb']
Join. This method combines paths. It receives two or more string arguments and combines them in an "intelligent" way. It will, for example, add a slash to the end of one argument.
Tip We access the join method by using its complete, composite name os.path.join. This requires no "from" in the import directive.
import os
# Join directory name not including slash.
result = os.path.join("C:\\programs", "file.py")
print(result)
# Join directory name with trailing slash.
result = os.path.join("C:\\programs\\", "file.py")
print(result)C:\programs\file.py
C:\programs\file.py
Split. With path.split we can separate the "folder" from the "file name." Pass a path string to path.split. It returns a tuple with two parts.
Part 1 The first part of the returned tuple is the folder path with no file name on it. The end slash is omitted.
Part 2 This is the file name. So it will be something like file.txt. It includes the extension.
Tip For file paths, please consider using raw string literals with an "r" prefix (unlike many of the examples on this page).
from os import path
example = r"C:\programs\file.txt"# Use split on path.
result = path.split(example)
# The result has two parts.
print("Result:", result)
# The second part of the tuple is the file name.
print("File name:", result[1])Result: ('C:\\programs', 'file.txt')
File name: file.txt
Timestamps. The path.getatime, path.getmtime and path.getctime methods get timestamps from files. These are the last-access time, the last-modified time, and (on Windows) the creation time.
Tip We get path timestamps, and convert them to dates. Please look for the example "File timestamps" in the Datetime page.
Summary. The file system provides useful information about files. The path methods in the os.path module are helpful for retrieving this information.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 10, 2024 (edit link).