Python study Note 10: path and file of the standard library (OS. path package, glob package ),

Source: Internet
Author: User
Tags glob

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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.