The Python standard library os.path package the glob package USES instances
- 2020-04-02 14:23:07
- OfStack
OS. The path
String path OS. Path package is mainly used for processing, such as'/home/zikong/doc/file. Doc ', to extract the useful information.
import os.path
path = '/home/zikong/doc/file.doc'
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 file names and directories and return them in a table
path2 = os.path.join('', 'home', 'zikong', 'doc', 'file.doc') # Use the directory name and file name to form a path string
p_list = [path, path2]
print(os.path.commonprefix(p_list)) # Query common parts of multiple paths
os.path.normpath(path) # Get rid of the path path Redundancy in. Such as '/home/vamei/../.' Be converted to '/home'
#os.path You can also query the file for information (metadata) . Information about the file is not stored inside the file, but by the operating system
# Maintain some information about the file ( Such as file type, size, modification time ) .
import os.path
path = '/home/vamei/doc/file.txt'
print(os.path.exists(path)) # Query for the existence of a file
print(os.path.getsize(path)) # Query file size
print(os.path.getatime(path)) # Query when the file was last read
print(os.path.getmtime(path)) # Query 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
Glob package
Glob is python's own file operation-related module with very little content, which allows you to find files that fit your purpose, similar to file search under Windows, and also supports wildcards, & # 63; ,[], representing 0 or more characters, ? Represents a character that [] matches a character in a specified range, such as [0-9] matches a number.
Glob method: returns a list of all matched file paths. This method requires an argument to specify the matched path string (which can be either an absolute or a relative path), for example:
import glob
glob.glob("/home/zikong/doc/*.doc")
/home/zikong/doc/file1.doc /home/zikong/doc/file2.doc
example
Combined use of two packages to write a similar to the ls function under Linux:
#coding = utf8
import glob
import os.path
path = '/Users/zikong/Pictures'
def ls(path):
#codinf = utf8
print "--name-- --type-- --size-- --atime-- --mtime-- "
path = path + '/*'
filelist = glob.glob(path)
for filepath in filelist:
out = '%s %s %s %s %s'%(filepath.split('/')[4] ,os.path.isfile(filepath) ,os.path.getsize(filepath) ,os.path.getatime(filepath) ,os.path.getmtime(filepath))
print out
ls(path)
Pay attention to
#coding=utf
It's for python to display Chinese