I. Introduction to the modules
The os module is Python's built-in module related to operating system functions and file systems.
Submodules of this module are modules specialized for path operations.
Commonly used path operations include determining whether a directory exists, creating a directory, deleting a directory, and traversing a directory.
Note: When using the module, it is recommended to use a string (Unicode) for the filename or path.
Since some Unix operating systems do not support Unicode strings, byte objects are required; whereas in Windows operating systems, it is recommended that all applications use string objects to access files.
The os module and its submodules are built-in modules that do not need to be installed and can be imported directly.
In a Python program, importing the os module with the import statement allows you to use both the properties and methods provided by the os module and the properties and methods provided by the module.
The code to import the os module is as follows:
import os # clarification:import (data) os post-modular,It is also possible to use its submodules 。
If only the content of the module is involved in the program, it can be imported directly with the following code:
import
Once you've imported a module using the code above, you can use the properties and methods provided by the module. If you're not sure what properties and methods the module provides, you can use Python's built-in function dir() to get a list of all its methods, as follows:
import # Modules for operating paths print(dir())
The program runs with the following results:
II. Commonly used methods
2.1 exists() method
Determine if a path exists (accurately)
The exists() method is used to determine whether a path (file or directory) exists, and returns True if it does, or False if it doesn't, or False if it's a broken symbolic link.
The syntax is formatted as follows:
(path)
Parameter Description:
- path: the path to be judged, you can use the absolute path, you can also use the relative path.
- Return value: True if the given path exists, otherwise False.
Note: When using the exists() method, if some platforms do not grant () execute permission on the requested file, using the method will return False even if the path actually exists.
Use the exists() method to determine if theE:\Code\lesson
directory of the Whether the file exists or not, the code is as follows:
import # Modules for operating paths path = r"E:\Code\lesson\" # Documentation if (path): # Determine if a file exists # E:\Code\lesson\ file exists print(path, "Document exists.") else: print(path, "File does not exist.")
Use the exists() method to determineE:\Code\lesson1
directory exists or not, the code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Modules for operating paths path = r"E:\Code\lesson1" # Catalog print((path)) # False if (path): # Determine if a directory exists print(path, "Catalog exists") else: # E:\Code\lesson1 Directory does not exist print(path, "Catalog does not exist.")
2.2 isdir() method
Determine if it is a directory
The isdir() method is used to determine if the specified path is a directory. The syntax format is as follows:
(path)
Parameter Description:
- path: the path to be judged, you can use the absolute path, you can also use the relative path.
- Return value: True if the given path is a directory, otherwise False.
Pass an absolute path into the isdir() method to determine if the path is a directory, as follows:
import # Imported modules print((r'E:/Code/lesson/')) # Determine if it is a directory False print((r'E:/Code/lesson/')) # Determine if it is a directory True
To get all the subdirectories under the specified directory, first apply the () method to get the list of directories and files under the specified path, then iterate through the list and connect the paths; then determine whether it is a directory, and if it is a directory, add it to the specified list; finally, print the list, the code is as follows:
import os # Documentation and operating system related modules root = r'E:/Code/lesson' path = (root) # Get a list of directories and files under a specified path list_dir = [] # Path List for item in path: # Iterate over the list of obtained directories and files p = (root, item) # Connect to the catalog if (p): # Determine if it's a catalog list_dir.append(p) print(f'catalogs:{list_dir}') # 打印catalogs列表
The program runs with the following results:
Directory: ['E:/Code/lesson\\.idea', 'E:/Code/lesson\\python-package']
2.3 isabs() method
Determine if the path is absolute
The isabs() method is used to determine if a path is an absolute path. The syntax format is as follows:
(path)
Parameter Description:
- path: the path to be judged, you can use the absolute path, you can also use the relative path.
- Return Value: True if the given path is an absolute path, otherwise False.
Note: On Unix systems, paths that begin with a slash are considered absolute; on Windows systems, those that begin with a (reverse) slash after the drive letter is removed are considered absolute.
Use isabs() method to determine whether the paths of the two files are absolute paths, and if not, convert them to absolute paths and output the code as follows:
import # Modules for operating paths path_list = [r'python-package/', r'E:\Code\lesson\python-package\demo', r'E:\Code\lesson\'] for path in path_list: # Traverse the catalog listings if not (path): # If it's not an absolute path path = (path) # Convert to absolute path print(path) # Printing individual paths
2.4 isf ile() method
Determine if a file is a normal file
The isfile() method is used to determine if a file is an ordinary file. The syntax format is as follows:
(path)
Parameter Description:
- path: the path to be judged, you can use the absolute path, you can also use the relative path.
- Return value: True if the file corresponding to the given path is an ordinary file, otherwise False.
The sample code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules print((r'E:\Code\lesson\')) # Determine if it's an ordinary file True # Description:Returns False if the specified file does not exist. print((r'E:\Code\lesson\')) # False path = r'E:\Code\lesson' # Catalog filename = '' # File name # When concatenating directories and filenames, it is not recommended to use the string splicing method to achieve this. # It is recommended to use the () method to achieve, the specific usage of the text will be explained in detail in subsequent subsections print(((path, filename))) # Determine if a file is a normal file True
2.5 The join() method
splice path
The join() method is used to join two or more paths together to form a new path. The syntax is as follows:
(path, *paths)
Parameter Description:
- path: the path of the file to be spliced.
- *paths: the paths of the files to be spliced, separated by commas. If there is no absolute path in the paths to be spliced, then the final spliced path will be a relative path.
- Return value: the path after stitching.
Note: When using the () function to splice a path, it does not check if the path actually exists.
The sample code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules print((r"E:\Code\lesson", "")) # Splicing strings # If more than one absolute path exists in the path to be spliced, then in left-to-right order, the last occurrence of the absolute path prevails. # and any arguments before the path are ignored, the code is as follows: # C:/demo print(('E:/Code', 'E:/Code/lesson', 'Code', 'C:/', 'demo')) # splice a string
2.6 abspath() method
Get absolute path
The abspath() method is used to return the absolute path to a file or directory. The syntax format is as follows:
(path)
Parameter Description:
- path: the relative path to get the absolute path, can be a file or a directory.
- Return Value: Returns the absolute path obtained.
Description: An absolute path is the actual path of a file specified when the file is used. It does not depend on the current working directory.
Note: The abspath() method does not check if the path actually exists when it gets the actual path, it just splices the current file directory with the path given by the abspath() method.
The sample code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules # E:\Code\lesson\python-package\demo4_os_path.py print((r'demo4_os_path.py')) # Print absolute paths # Use the abspath() method to get the absolute path to the current Python file, as follows: print(((__file__))) print((__file__))
2.7 The basename() method
Extract file names from a path
The basename() method is used to extract a filename from a path. When the specified path is a path that does not include a filename (such as theE:\Code\lesson\
), the empty string is returned. The syntax is formatted as follows:
(path)
Parameter Description:
- path: the path of the file name to be extracted.
- Return Value: Returns the name of the extracted file.
The sample code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules # print((r"demo\")) # Print the file name path1 = 'e:/demo/' path2 = 'e:/demo' path3 = r'E:/Code/lesson/' print((path1)) # print((path2)) # demo # If path ends with / or \, then null is returned. print((path3)) # ""
2.8 dirname() method
Get the directory in the path
The dirname() method is used to extract a directory from a path. It is equivalent to the first element obtained after splitting a path using the () method. The syntax format is as follows:
(path)
Parameter Description:
- path: indicates the path of the directory to be extracted.
- Return Value: Returns the extracted directory.
The sample code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules print((r"E:\Code\lesson\python-package\demo\")) print((r"demo/"))
2.9 The split() method
Split Path Name
The split() method is used to split directories and filenames from a path. The syntax format is as follows:
(path)
Parameter Description:
- path: the path to be split, either absolute path or relative path.
- Return Value: Returns a tuple, the same as the tuple returned by ((), ()). If a relative path is specified and ends with a slash, the second element of the returned tuple is empty.
Use the split() method to split the disk, folder and file names from the absolute path, the sample code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules lesson_path = r'E:/Code/lesson' # Path to the code folders = [] drive, path_and_file = (lesson_path) # Split drives and directories (drive[0]) # Get the disk letter in the drive path, file = (path_and_file) # Split paths and filenames if path != '': # Processing path for i in ('/'): # Separate paths by / if i != '': (i) if file != '': # Processing filenames (file) print(folders) # Print Separation Results
2.10 The splitext() method
Splitting file names and extensions
The splitext() method is used to split the base filename and extension from a path. The syntax format is as follows:
(path)
Parameter Description:
path: the path to be split, either absolute path or relative path.
Return value: returns a tuple whose first element is the string representation of the base filename (the part of the path other than the extension), and whose second element is the string representation of the extension (the part of the path that includes the.
number). If the specified path does not include an extension, the second element of the returned tuple is the empty string.
The sample code is as follows:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules print((r'E:/amo/test/pdf/')) # Split absolute paths print((r'E:/amo/test/pdf/')) # Split absolute paths without filenames print((r'amo/mot_cn.txt')) # Split relative paths word_path = r'E:/amo/test/pdf/' # Path to Word document split_path = (word_path) # Split the path of a Word document pdf_path = split_path[0] + '.pdf' # Combine paths to PDF documents print(f'generatedPDFfile path:{pdf_path}')
2.11 supports_unicode_f ilenames attribute
Marks whether the file system supports Unicode filenames.
The supports_unicode_filenames property is used to mark whether the current file system supports Unicode filenames. The syntax is as follows:
.supports_unicode_filenames
Parameter Description:
- Return Value: True if the file system supports Unicode filenames.
Use the supports_unicode_filenames property to determine if the current system supports Unicode filenames. If so, create theMotto.txt
file, otherwise create the file with the following code:
# -*- coding: utf-8 -*- # @Time : 2022-07-04 0:15 # @Author : AmoXiang # @File : demo4_os_path.py # @Software: PyCharm # @Blog : /xw1680 import # Imported modules filename = '' # Variables that hold file names print(.supports_unicode_filenames) # True if .supports_unicode_filenames: # Determine if Unicode file names are supported filename = r'Motto.txt' else: filename = r'' open(filename, 'w') # Create or open files # File name: motto.txt print('The file name is:', filename) # Print file name
To this article on the Python commonly used basic modules of the module details of the article is introduced to this, more related Python module content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!