Python study Note 10: path and file of the standard library (OS. path package, glob package ),
One OS. path package
Check the Code:
Import OS. pathpath = "/home/User/Document/test.txt" print (OS. path. basename (path) # query the file name print (OS. path. dirname (path) # The query path contains the directory 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', 'user', 'document', 'file1.txt ') # use the directory name and file name to form a path string print (path2) p_list = [path, path2] print (OS. path. commonprefix (p_list) # query the common parts of multiple paths
Output:
Test.txt
/Home/User/Document
('/Home/User/document', 'test.txt ')
/Home \ User \ Document \ file1.txt
/Home
There are also:
Print (OS. path. exists (path) # query whether a file exists
Print (OS. path. getsize (path) # query the file size
Print (OS. path. getatime (path) # query the last file read time
Print (OS. path. getmtime (path) # query the last file modification time
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
Two glob packages
The most common method of a glob package is glob. glob (). The function of this method is similar to that of ls in Linux.
Accepts a Linux File Name format expression (filename pattern expression ),
List all files that match the expression (similar to the regular expression) and put all file names in a table to return.
Therefore, glob. glob () is a good way to query files in a directory.
The syntax of the file name expression is different from that of the Python regular expression. The correspondence is roughly as follows:
Filename Pattern Expression Python Regular Expression
*.*
? .
[0-9] same
[A-e] same
[^ Mnp] same