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.
Python program that uses commonprefix
from os import path
# Add paths to a list.
paths = 
# Get common prefix of the paths.
prefix = path.commonprefix(paths)
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.
Python program that lists files in folder
# 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.
Python program that uses join
# Join directory name not including slash.
result = os.path.join("C:\\programs", "file.py")
# Join directory name with trailing slash.
result = os.path.join("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.
First part The first part of the returned tuple is the folder path with no file name on it. The end slash is omitted.
Second part This is the file name. So it will be something like file.txt. It includes the extension.
Raw literals For file paths, please consider using raw string literals with an "r" prefix (unlike many of the examples on this page).
Python program that uses path.split
from os import path
example = r"C:\programs\file.txt"# Use split on path.
result = path.split(example)
# The result has two parts.
# The second part of the tuple is the file name.
print("File name:", result)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.