Home > Article > Backend Development > python file path operation
import os.path
path = '/home/vamei/doc/file.txt'
print(os.path.basename(path)) #Query the file name contained in the path
print(os .path.dirname(path)) # Query the directory contained in the path
info = os.path.split(path) # Split the path into two parts: file name and directory, put them in a table and return
print(info)
path2 = os.path.join('/', 'home', 'vamei', 'doc', 'file1.txt') # Use the directory name and file name to form a path string, string Splicing output:/homevameidocfile1.txt
p_list = [path, path2]
print(os.path.commonprefix(p_list)) #Query the common parts of multiple paths
os.path.normpath (path) # Remove redundancy in the path. For example, '/home/vamei/../.' is converted to '/home'
print(os.path.exists(path)) # Check whether the file exists
print( os.path.getsize(path)) #Query the file size
print(os.path.getatime(path)) #Query the time when the file was last read
print(os.path.getmtime(path)) #Query The time when the file was last modified
print(os.path.isfile(path)) # Whether the path points to a regular file
print(os.path.isdir(path)) # Whether the path points to a directory file