Introduction of python os Module and fnmatch Module

  • 2021-09-20 21:11:20
  • OfStack

Directory 1. First introduce os module 1, split path method 2, build file path method 3, obtain file attribute method 4, judge file type 5, file and directory operation 6, modify file attribute and judge file attribute 7, traverse directory tree 2. fnmatch module 1, wildcard characters supported by fnmatch are as follows 2, common methods of fnmatch 3, fnmatch. fnmatch method 4, fnmatch. filter method 4, fnmatch

1. First introduce the os module under 1


import os
 
print(os.getcwd())
# E:\python\test\python_models
#  Get the 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 1 List 

1. Introduction to the method of splitting the path


# 1 Introduction to the method of splitting paths 
# os.path Module is used to manage the file and path process, showing that it contains many functions of splitting paths. os.path The functions related to the split path in the module are 
 
# os.path.split()   Return 1 A 2 Tuple, containing the path and file name of the file 
# os.path.dirname()   Returns the path of the file 
# os.path.basename()    Returns the file name of the file 
# os.path.splitext()      Return 1 Parts that do not include the file extension and the file extension 2 Tuple 
 
#  The following demonstration 1 The method described above below 
path = "G:\ New Folder \ Madness \ Permanent address .txt"
 
print(os.path.split(path))
# ('G:\\ New Folder \\ Madness ', ' Permanent address .txt')
 
print(os.path.dirname(path))
# G:\ New Folder \ Madness 
 
print(os.path.basename(path))
 
print(os.path.splitext(path))
# ('G:\\ New Folder \\ Madness \\ Permanent address ', '.txt')

2. Introduction to the method of building file path


# 2 Introduction to the method of building a path 
# python Engineers can use os.path Module convenient splitting path, corresponding, os.path Module also contains functions to build paths, the most commonly used of which are 
 
# os.path.expanduser()     Expand the user's HOME Directory , For example ~ , ~username
# os.path.abspath()          Get the absolute path of a file or path 
# os.path.join()               Splice paths with different path separators according to different operating system platforms 
 
#  The following demonstration 1 The method described above below 
# os.path.expanduser("~mysql")  Return mysql User's HOME Directory, I have here windows Platform, I won't demonstrate this command 
 
 
print(os.path.abspath("."))
# E:\python\test\python_models
 
print(os.path.abspath(".."))
# E:\python\test
 
#  Correspondingly, there are 1 There are three ways to judge 1 Are the paths absolute 
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 the __file__ This special variable represents the source file where the current code is located. When writing code, sometimes it is necessary to import the software package under the parent directory of the current source file, so it is necessary to use 
#  The path function here gets 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. Introduction to the method of obtaining file attributes


# 3 Gets the file properties 
# os.path Module also contains several functions to obtain the file attributes, including file creation time, modification time, file size, access time 
# os.path.getatime()         Returns the access time of the file 
# os.path.getmtime()           Returns the time when the file was modified 
# os.path.getctime()           Returns the time when the file was created 
# os.path.getsize()            Returns the size of the file 

4. Determine the type of file


# 4 To determine the file type 
# os.path The module also provides several functions to determine whether the path exists or not and the type of file the path refers to. These functions determine the class 1 As with is Start, and returns the 1 A Boolean The result of type 
 
# os.path.exists()       Parameter path Does the path pointed to exist 
# os.path.isfile()         Parameter path The path pointed to exists and is a file 
# os.path.isdir()            Parameter path The path pointed to exists and is a directory 
# os.path.islink()             Parameter path The path pointed to exists and is 1 Connections 
# os.path.ismount()             Parameter path The path pointed to exists and is 1 Mount points 

5. File and directory operations


# 5 Operation of files and directories 
# os Module preserves the operation functions of files and directories, including creating directories, deleting directories, deleting files, renaming files and so on 
# os.remove()       Delete path File pointed to by path 
# os.rmdir()          Delete path The folder pointed to by the path lock, which must be empty, otherwise a failure will be reported 
# os.mkdir()          Create 1 Folders 
# os.rename()         Rename 1 Files or folders 

6. Modify file attributes and judge file attributes


# 6 Modify file permissions and determine file permissions 
# os Module also contains functions to modify file permissions and judge file permissions, namely chmod And access , chmod The permissions used to modify the file, access Used to determine whether a file has corresponding permissions, in the linux In, 
#  Permissions are divided into read, write, and execute, so os Module also provides 3 Constants to represent read, write and execute, that is, 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. Traverse the directory tree


# 7 , os.walk Traverse the directory tree 
#  The previous examples are all about finding a certain 1 File under the directory and through pattern matching to choose their own file type, in the actual work, more likely to encounter is to find a directory and its subdirectories under all the files 
#  . For example, find all the pictures in a certain directory and its subdirectories, and find the largest pictures in a certain directory and its subdirectories 10 Files , For such requirements, you can use the os Module walk Method, walk Method traverses a directory and its 
#  Subdirectory, for each 1 Directories, walk Return 1 A 3 Tuples, dirpath , dirnames , filenames , of which dirpath The current directory is saved, dirnames Is a list of subdirectories under the current directory, filenames
#  Is a 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 Directory under the current directory 
    # c Is a file in the current directory 

2. Introduction to the fnmatch module


# 8 Find files 
#  Use fnmatch To find specific files, in most cases, using string matching to find specific files is enough. If you need more flexible string matching, you can use the fnmatch Library, this library 
#  It is specially used for file name matching, and supports the use of wildcard characters for file name matching 

1. Wildcard characters supported by fnmatch are as follows


# fnmatch Supported wildcard characters are as follows 
# *            Matches any number of characters 
# ?            Match a single character 
# [sep]        Matching sep Characters in the 
# [!sep]       Matching except sep Any character thought 

2. Introduction of common methods of fnmatch


# 1 Introduction to the method of splitting paths 
# os.path Module is used to manage the file and path process, showing that it contains many functions of splitting paths. os.path The functions related to the split path in the module are 
 
# os.path.split()   Return 1 A 2 Tuple, containing the path and file name of the file 
# os.path.dirname()   Returns the path of the file 
# os.path.basename()    Returns the file name of the file 
# os.path.splitext()      Return 1 Parts that do not include the file extension and the file extension 2 Tuple 
 
#  The following demonstration 1 The method described above below 
path = "G:\ New Folder \ Madness \ Permanent address .txt"
 
print(os.path.split(path))
# ('G:\\ New Folder \\ Madness ', ' Permanent address .txt')
 
print(os.path.dirname(path))
# G:\ New Folder \ Madness 
 
print(os.path.basename(path))
 
print(os.path.splitext(path))
# ('G:\\ New Folder \\ Madness \\ Permanent address ', '.txt')
0

3. Introduction of fnmatch. fnmatch method


# 1 Introduction to the method of splitting paths 
# os.path Module is used to manage the file and path process, showing that it contains many functions of splitting paths. os.path The functions related to the split path in the module are 
 
# os.path.split()   Return 1 A 2 Tuple, containing the path and file name of the file 
# os.path.dirname()   Returns the path of the file 
# os.path.basename()    Returns the file name of the file 
# os.path.splitext()      Return 1 Parts that do not include the file extension and the file extension 2 Tuple 
 
#  The following demonstration 1 The method described above below 
path = "G:\ New Folder \ Madness \ Permanent address .txt"
 
print(os.path.split(path))
# ('G:\\ New Folder \\ Madness ', ' Permanent address .txt')
 
print(os.path.dirname(path))
# G:\ New Folder \ Madness 
 
print(os.path.basename(path))
 
print(os.path.splitext(path))
# ('G:\\ New Folder \\ Madness \\ Permanent address ', '.txt')
1

4. Introduction of fnmatch. filter method


# 1 Introduction to the method of splitting paths 
# os.path Module is used to manage the file and path process, showing that it contains many functions of splitting paths. os.path The functions related to the split path in the module are 
 
# os.path.split()   Return 1 A 2 Tuple, containing the path and file name of the file 
# os.path.dirname()   Returns the path of the file 
# os.path.basename()    Returns the file name of the file 
# os.path.splitext()      Return 1 Parts that do not include the file extension and the file extension 2 Tuple 
 
#  The following demonstration 1 The method described above below 
path = "G:\ New Folder \ Madness \ Permanent address .txt"
 
print(os.path.split(path))
# ('G:\\ New Folder \\ Madness ', ' Permanent address .txt')
 
print(os.path.dirname(path))
# G:\ New Folder \ Madness 
 
print(os.path.basename(path))
 
print(os.path.splitext(path))
# ('G:\\ New Folder \\ Madness \\ Permanent address ', '.txt')
2

The above is the python os module and fnmatch module of the use of the introduction of the details, more about python os module and fnmatch module information please pay attention to other related articles on this site!


Related articles: