Introduction to Python OS module and fnmatch module

Time:2021-10-25

1、 First introduce the OS module

?
1
2
3
4
5
6
7
8
9
10
import os
 
print(os.getcwd())
# E:\python\test\python_models
#Get current directory
 
 
print(os.listdir("."))
# ['oop.py', 'python_argparse.py', 'python_click.py', 'python_os.py', 'python_re.py', 'python_requests.py', 'xx.py', '__init__.py']
#Lists all files and folders in the specified directory, and returns a list

1. Introduction to splitting paths

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#1. Introduction to splitting paths
#The os.path module is used to manage files and path processes. It shows that it contains many functions for splitting paths. The functions related to splitting paths in the os.path module are
 
# os.path.split()   Returns a binary containing the path and file name of the file
# os.path.dirname()   Returns the path to the file
# os.path.basename()    Returns the file name of the file
# os.path.splitext()      Returns a binary that does not include the file extension and the file extension
 
#Let's demonstrate the method described above
path = "G: \ new folder \ crazy \ permanent address. TXT"
 
print(os.path.split(path))
#('g: \ \ new folder \ \ crazy ',' permanent address. TXT ')
 
print(os.path.dirname(path))
#G: \ new folder \ crazy
 
print(os.path.basename(path))
 
print(os.path.splitext(path))
#('g: \ \ new folder \ \ crazy \ \ permanent address', '. TXT')

2. How to build a file path

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#2. Introduction to the method of constructing path
#Python engineers can use the os.path module to easily split paths. Accordingly, the os.path module also contains functions to build paths, of which the most commonly used is
 
# os.path.expanduser()     Expand the user's home directory, such as ~, ~ username
# os.path.abspath()          Get the absolute path of the file or path
# os.path.join()               Different path separators are used to splice paths according to different operating system platforms
 
#Let's demonstrate the method described above
#Os.path.expanduser ("~ MySQL") returns the home directory of the MySQL user. This is the windows platform, so I won't demonstrate this command
 
 
print(os.path.abspath("."))
# E:\python\test\python_models
 
print(os.path.abspath(".."))
# E:\python\test
 
#Accordingly, there is a method to judge whether a path is an absolute path
print(os.path.isabs("."))
# False
print(os.path.isabs(os.path.abspath(".")))
# True
 
 
print(os.path.join(os.path.abspath("."),"test","join.text"))
# E:\python\test\python_models\test\join.text
 
#In Python code, you can use__ file__ This special variable represents the source file of the current code. When writing code, you sometimes need to import the software package under the parent directory of the current source file, so you need to use it
#The path function here obtains the parent directory of the source file, as shown below
path = os.path.abspath(__file__)
print(path)
# E:\python\test\python_models\python_os.py
 
print(os.path.dirname(path))
# E:\python\test\python_models
 
print(os.path.pardir)
# ..
 
print(os.path.abspath(os.path.join(os.path.dirname(path),os.path.pardir)))
# E:\python\test

3. How to get file attributes

?
1
2
3
4
5
6
#3. Get file attributes
#The os.path module also contains several functions to obtain the attributes of the file, including the file creation time, modification time, file size and access time
# os.path.getatime()         Returns the time the file was accessed
# os.path.getmtime()           Returns the time when the file was modified
# os.path.getctime()           Returns the creation time of the file
# os.path.getsize()            Returns the size of the file

4. Determine the type of file

?
1
2
3
4
5
6
7
8
#4. Judge the document type
#The os.path module also provides several functions to determine whether the path is saved or not and the type of file the path refers to. These functions of the judgment class generally start with is and return a boolean result
 
# os.path.exists()       Whether the path pointed to by the parameter path exists
# os.path.isfile()         The path pointed to by the parameter path exists and is a file
# os.path.isdir()            The path pointed to by the parameter path exists and is a directory
# os.path.islink()             The path pointed to by the parameter path exists and is a connection
# os.path.ismount()             The path pointed to by the parameter path exists and is a mount point

5. File and directory operations

?
1
2
3
4
5
6
#5. Operation of files and directories
#The OS module retains the operation functions of files and directories, including creating directories, deleting directories, deleting files, renaming files, etc
# os.remove()       Delete the file pointed to by the path
# os.rmdir()          Delete the folder pointed to by the path lock. The folder must be empty, or failure will be reported
# os.mkdir()          Create a folder
# os.rename()         Rename a file or folder

6. Modify file attributes and judge file attributes

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#6. Modify file permissions and judge file permissions
#The OS module also contains functions to modify file permissions and judge file permissions, namely Chmod and access. Chmod is used to modify file permissions, and access is used to judge whether files have corresponding permissions. In Linux,
#Permissions are divided into read, write and execute. Therefore, the OS module also provides three constants to represent read, write and execute, namely R_ OK,W_ OK,X_ OK
 
 
print(os.access(__file__,os.R_OK))
# True
 
print(os.access(__file__,os.W_OK))
# True
print(os.access(__file__,os.X_OK))
# True
 
os.chmod(__file__,os.W_OK)

7. Traversing the directory tree

?
1
2
3
4
5
6
7
8
9
10
11
12
#7. Os.walk traverses the directory tree
#The previous examples are to find the files in a directory and select the file type you need through pattern matching. In practical work, you are more likely to find all the files in a directory and its subdirectories
# For example, find all the pictures in a directory and its subdirectories, and find the ten largest files in a directory and its subdirectories. For such requirements, you can use the OS module walk method, which traverses a directory and its subdirectories
#Subdirectories. For each directory, walk returns a triple, dirpath, dirnames and filenames, where dirpath saves the current directory, dirnames is the list of subdirectories under the current directory, and filenames
#Is the list of files in the current directory
 
for a,b,c in os.walk(".."):
    print(a,b,c,"walk---------")
 
    #A is the current directory
    #B is the directory under the current directory
    #C is the file in the current directory

2、 Introduction to fnmatch module

?
1
2
3
#8. Find files
#Use fnmatch to find specific files. In most cases, using string matching to find specific files can meet the requirements. If more flexible string matching is required, you can use the fnmatch Library in the standard library
#It is specially used for file name matching. Wildcards are supported for file name matching

1. The wildcards supported by fnmatch are as follows

?
1
2
3
4
5
#The wildcards supported by fnmatch are as follows
# *            Match any number of characters
#            Match single character
# [sep]        Match characters in Sep
# [!sep]       Matches any character except Sep

2. Introduction to common methods of fnmatch

?
1
2
3
4
5
#Common methods of fnmatch
# fnmatch.fnmatch()     Determine whether the file name conforms to a specific pattern and is case sensitive
# fnmatch.fnmatchcase()   Determine whether the file name conforms to a specific module, and is not case sensitive
# fnmatch.filter()        Returns a list of file names that match a specific pattern in the input list
# fnmatch.translate()      Convert wildcard matching patterns to regular expressions

3. Introduction to fnmatch.fnmatch method

?
1
2
3
4
5
6
7
8
9
10
for file in os.listdir("."):
    if fnmatch.fnmatch(file,"*.html"):
        print(file)
 
    elif fnmatch.fnmatch(file,"[a-z]??.py"):
        print(file,"hahah")
    elif fnmatch.fnmatch(file,"[!a-o]*"):
        print(file)
    else:
        pass

4. Introduction to fnmatch.filter method

?
1
2
3
    
#The filter method is the same as fnmatch, except that the filer needs to pass a list of files and return a list that meets the matching rules
print(fnmatch.filter(os.listdir("."),"*py"))

The above is the details of the introduction to the use of Python OS module and fnmatch module. For more information about Python OS module and fnmatch module, please pay attention to other relevant articles of developepper!