You must have used functions provided by the os module in Python several times in your projects. These could be used to create a file, walk down a directory, get info on the current directory, perform path operations, and more.
In this article, we’ll discuss the functions that are as useful as any function in the os module but are rarely used.
os.path.commonpath()
When working with multiple files that share a common directory structure, you might want to find the longest shared path. os.path.commonpath() does just that. This can be helpful when organizing files or dealing with different paths across environments.
Here’s an example:
import os
paths = ['/user/data/project1/file1.txt', '/user/data/project2/file2.txt']
common_path = os.path.commonpath(paths)
print("Common Path:", common_path)
This code will give us the common path shared by these two paths.
Common Path: /user/data
You can see that os.path.commonpath() takes a list of path names, which might be impractical to manually write them down.
In that case, it is best to iterate over all of the directories, subdirectories, and file names and then look for the common path.
import os
def get_file_paths(directory, file_extension=None):
# Collect all file paths in the directory (and subdirectories, if any)
file_paths = []
for root, dirs, files in os.walk(directory):
for file in files:
if file_extension is None or file.endswith(file_extension):
file_paths.append(os.path.join(root, file))
return file_paths
# Specify the root directory to start from
directory_path = 'D:/SACHIN/Pycharm/Flask-Tutorial'
# If you want to filter by file extension
file_paths = get_file_paths(directory_path, file_extension='.html')
# Find the common path among all files
if file_paths:
common_path = os.path.commonpath(file_paths)
print("Common Path:", common_path)
else:
print("No files found in the specified directory.")
In this example, the function get_file_paths() traverses a directory from top to bottom and appends all the paths found in the file_paths list. This function optionally takes a file extension if we want to look out for specific files.
Now we can easily find the common path of any directory.
Common Path: D:\SACHIN\Pycharm\Flask-Tutorial\templates
os.scandir()
If you’re using os.listdir() to get the contents of a directory, consider using os.scandir() instead. It’s not only faster but also returns .
✅.
✅?
✅How does the learning rate affect the ML and DL models?
That’s all for now.
Keep Coding✌✌.
SOCIAL SHARE CARD GENERATOR