Hello, I’m Yue Chuang.
Official account: AI Yue Chuang, original blog: www.aiyc.top/1914.html
This article is to improve the Python Office automation course. If you are interested in signing up for one-to-one office automation, you can add V: Jiabcdefh.
If we want to operate files and directories, you can enter various commands provided by the operating system below the command line to complete. For example, dir and cp.
What if you want to perform these directory and file operations in a Python program?
The commands provided by the operating system simply call the interface functions provided by the operating system. Python’s built-in OS module can also directly call the interface functions provided by the operating system.
1. Introduction
OS is the abbreviation of “Operating System”. As the name implies, OS module provides an interface for various Python programs to interact with the operating system. By using OS modules, on the one hand, you can easily interact with the operating system, and on the other hand, the page can greatly enhance the portability of code. An OSError exception or one of its subclasses is raised if the module fails.
Note: This module provides a convenient way to use operating system-specific features. For reading and writing files, we recommend using the built-in open() function; For path-related operations, you are advised to use the OS submodule os.path. If you want to read multiple files line by line, the FileInput module is recommended; To create temporary files or paths, the tempFile module is recommended; For more advanced file and path manipulation, use the shutil module.
Of course, just because you can write operating system-independent code using OS modules doesn’t mean that the OS can’t call some system-specific extensions, but it’s important to keep in mind that doing so can greatly impair the portability of your code.
In addition, import OS module also be careful, do not call in order to save trouble and OS module unpack import, that is, do not use:
from os import *
Copy the code
To import the OS module; Otherwise, os.open() will override the built-in function open(), causing unexpected errors.
2. Common functions
Note that most functions in OS modules that accept a path as an argument can also accept a “file descriptor” as an argument.
File descriptor: File descriptor, abbreviated as fd in The Python documentation, is an integer bound to an open file object, which can be interpreted as the number of the file in the system.
OS 2.1. The name
This property broadly indicates the environment in which Python is currently running, and is actually the name of the imported operating system-related module. This name also determines which functions are available in a module and which are not implemented accordingly.
Currently, the valid names are POSIX, NT, and Java.
Among them:
posix
Portable Operating System Interface of UNIX (Portable Operating System Interface) Linux and Mac OS both return this value;nt
The full name is Microsoft Windows NT, which is roughly equivalent to the Windows operating system. Therefore, the value is returned in Windows.java
Is the returned value in the Java VIRTUAL machine environment.
Bottom line: If posiX, the system is Linux, Unix, or Mac OS X. If NT, it’s Windows.
So execute the following code on my computer (Win10) and return nt:
In [1] :import os
In [2]: os.name
Out[2] :'nt'
Copy the code
The result on WSL (Windows Subsystem Linux) is:
In [2]: import os
In [3]: os.name
Out[3]: 'posix'
Copy the code
Look at the sys.platform property in the SYS module for more detailed information about the running platform, which is not covered here
Windows 10:
In [4]: sys.platform
Out[4] :'win32'
Copy the code
Linux:
In [5]: sys.platform
Out[5] :'linux'
Copy the code
PS: To get detailed system information, call the uname() function:
In [6]: os.uname()
Out[6]: posix.uname_result(sysname='Linux', nodename='aiyc', release='5.11.0-34 - generic', version='#36~20.04.1-Ubuntu SMP Fri Aug 27 08:06:32 UTC 2021', machine='x86_64')
Copy the code
Note that the uname() function is not provided on Windows, which means that some functions of the OS module are operating system specific.
2.2 Environment variables Os. environ
The OS. environ attribute returns environment-specific information, mainly environment variables. The return value is a mapping (similar to dictionary type). The specific value is the snapshot when the OS module is imported for the first time. In each of the key-value pairs, the key is the name of the environment variable and the value is the corresponding value of the environment variable. The value of this attribute does not change after the first import of the OS module unless the value of OS. environ is changed directly.
All environment variables defined in the operating system are stored in the os.environ variable and can be viewed directly:
In [8]: os.environ
Out[8]:
environ{'ALLUSERSPROFILE': 'C:\\ProgramData'.'ANSICON': '75x32766 (75x24)'.'ANSICON_DEF': '7'.'APPDATA': 'C:\\Users\\clela\\AppData\\Roaming'.'CHOCOLATEYINSTALL': 'C:\\ProgramData\\chocolatey'.'CHOCOLATEYLASTPATHUPDATE': '132726379469707878'.'CLASSPATH': '; C:\\java\\lib\\dt.jar; C:\\java\\lib\\tools.jar; '.'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files'. }Copy the code
To get the value of an environment variable, call os.enviro.get (‘key’), for example, where the key is “HOMEPATH” (” HOME “on Windows,” HOME “on Linux), which corresponds to the path to the user’s HOME directory. On Windows, the value is:
In [9]: os.environ["HOMEPATH"]
Out[9]: '\\Users\\clela'
Copy the code
Under Linux, the value is:
In [17]: os.environ["HOME"]
Out[17]: '/home/aiyc'
Copy the code
2.3 OS. Walk ()
This function takes a path as top. The function walks through a directory tree with top as the root node and generates a triple of (dirpath, dirnames, filenames) for each directory in the tree.
Among them:
dirpath
Is a string indicating the path to the directory,dirnames
Is adirpath
Subdirectory name (remove"."
和".."
)The list of ,filenames
bydirpath
A list of all non-directory filenames under.- Note that these names do not contain the path itself
dirpath
The next file or path fromtop
The full path to the start of the directory, which needs to be usedos.path.join(dirpath, name)
。
Note that the final result is an iterator. We can use the for statement to get each item of the iterator one by one:
for item in os.walk(".") :print(item)
Copy the code
[' ('. ',do'], ['go_go_go.txt'])
('.\\do', ['IAmDirectory', 'python'], [])
('.\\do\\IAmDirectory', [], [])
('.\\do\\python', [], ['hello_justdopython.txt'])
Copy the code
Example 2:
import os
for pt in os.walk(".") :print(pt)
Copy the code
('.', ['Tester2Folder', 'TesterFolder'], [' OS-alexSmith_2021 - copy (2).txt', 'OS-alexsmith_2021 - copy (3).txt', 'OS-alexSmith_2021. TXT ',' OS-alexSmith_2021. TXT ', 'OS-i_have_a_dream - copy (2TXT ', 'os-i_have_a_dream.txt ',' OS-i_have_a_dream.txt ', 'OS-i_have_a_dream.txt ',' OS-wordcount_basic - copy (2). P y ', 'OS - WordCount_Basic - copy. P y', 'OS - WordCount_Basic. P y', 'OS_Page. Py']) (' \ \ Tester2Folder ', ['Tester2Folder_test'], ['Tester2Folder-AlexSmith_2021 - Copy (2).txt', 'Tester2Folder-AlexSmith_2021 - copy (3).txt', 'Tester2Folder-AlexSmith_2021 - copy (4).txt', 'tester2Folder-alexSmith_2021. TXT ',' tester2Folder-alexSmith_2021. TXT ', 'Tetser2-WordCount_Basic.py']) ('.\\Tester2Folder\\Tester2Folder_test', [], []) ('.\\TesterFolder', [], TXT ', 'testerfolder-i_have_a_dream. TXT ',' testerfolder-i_have_a_dream. TXT ', 'Testerfolder-i_have_a_dream - copy (2).txt', 'testerFolder-tester-i_have_a_dream - copy (3).txt', 'TesterFolder-WordCount_Basic.py'])
Copy the code
2.4 OS. Listdir ()
Listdir is a list directories that list all the paths (and files) in the (current) directory. The function takes an argument that specifies the path to list the subdirectories. The default is., or “current path.”
The return value of the function is a list of elements as strings, pathnames and file names.
This is often useful in scenarios where you need to traverse files in a folder.
For example, define the following functions:
import os
def get_filelists(file_dir='. ') :
list_directory = os.listdir(file_dir)
filelists = []
for directory in list_directory:
The # os.path module will be covered later
if os.path.isfile(directory):
filelists.append(directory)
return filelists
Copy the code
The return value of this function is a list of all files in the current directory rather than a list of folder names.
2.5 OS. The mkdir ()
Mkdir, or make directory, is used to create a path. A classpath parameter is passed to specify the location and name of the new path, and an FileExistsError exception is raised if the specified path already exists.
This function can only create a tier 1 path under an existing path, otherwise (creating a multilevel path) will raise FileNotFoundError.
Accordingly, in scenarios where new multilevel paths are required, os.makedirs() can be used to accomplish this task. The os.makedirs() function performs recursive creation, creating, if necessary, intermediate paths through which the specified path passes, until the final “leaf path” is created.
Example 1:
>>> os.mkdir("test_os_mkdir")
>>> os.mkdir("test_os_mkdir")
Traceback (most recent call last):
File "<stdin>", line 1.in <module>
FileExistsError: [WinError 183] Cannot create a file that already exists. :'test_os_mkdir'
>>>
>>> os.mkdir("test_os_mkdir/test_os_makedirs/just/do/python/hello")
Traceback (most recent call last):
File "<stdin>", line 1.in <module>
FileNotFoundError: [WinError 3] The system could not find the specified path. :'test_os_mkdir/test_os_makedirs/just/do/python/hello'
>>>
>>> os.makedirs("test_os_mkdir/test_os_makedirs/just/do/python/hello")
Copy the code
Example 2:
In [1] :import os
In [2]: os.getcwd()
Out[2] :'D:\\Curriculum- Development \\ Office automation \\Coder\ 02- File operation \\OS_Module_Code'
In [3] :for path in os.walk('. ') :... :print(path) ... : ('. '['Tester2Folder'.'TesterFolder'], ['OS-alexSmith_2021 - copy (2).txt'.'OS-alexSmith_2021 - copy (3).txt'.'OS-AlexSmith_2021 - 副本.txt'.'OS-AlexSmith
_2021.txt'.'OS-i_have_A_dream - copy (2).txt'.'OS-i_have_a_dream - copy.txt'.'OS-I_Have_a_Dream.txt'.'OS-wordcount_basic - copy (2).py'.'os-wordcount_basi C - copy.py'.'OS-WordCount_Basic.py'.'OS_Page.py'])
('.\\Tester2Folder'['Tester2Folder_test'], ['Tester2Folder-AlexSmith_2021 - Copy (2).txt'.'Tester2Folder-AlexSmith_2021 - Copy (3).txt'.'Tester2Folder-Alex Smith_2021 - Copy (4).txt'.'Tester2Folder- alexSmith_2021-copy.txt '.'Tester2Folder-AlexSmith_2021.txt'.'Tetser2-WordCount_Basic.py'])
('.\\Tester2Folder\\Tester2Folder_test', [], [])
('.\\TesterFolder', [], ['TesterFolder-I_Have_a_Dream - copy.txt '.'TesterFolder-I_Have_a_Dream.txt'.'TesterFolder-tester-i_have_a_dream - Copy (2).txt'.'Tes terfolder-Tester-i_have_a_dream - copy (3).txt'.'TesterFolder-WordCount_Basic.py'])
In [4]: os.mkdir("aiyc")
In [5] :for path in os.walk('. ') :... :print(path) ... : ('. '['aiyc'.'Tester2Folder'.'TesterFolder'], ['OS-alexSmith_2021 - copy (2).txt'.'OS-alexSmith_2021 - copy (3).txt'.'OS-AlexSmith_2021 - 副本.txt'.'OS-A
lexSmith_2021.txt'.'OS-i_have_A_dream - copy (2).txt'.'OS-i_have_a_dream - copy.txt'.'OS-I_Have_a_Dream.txt'.'OS-wordcount_basic - copy (2).py'.'OS-wordco unt_Basic - copy.py'.'OS-WordCount_Basic.py'.'OS_Page.py'])
('.\\aiyc', [], [])
('.\\Tester2Folder'['Tester2Folder_test'], ['Tester2Folder-AlexSmith_2021 - Copy (2).txt'.'Tester2Folder-AlexSmith_2021 - Copy (3).txt'.'Tester2Folder-Alex Smith_2021 - Copy (4).txt'.'Tester2Folder- alexSmith_2021-copy.txt '.'Tester2Folder-AlexSmith_2021.txt'.'Tetser2-WordCount_Basic.py'])
('.\\Tester2Folder\\Tester2Folder_test', [], [])
('.\\TesterFolder', [], ['TesterFolder-I_Have_a_Dream - copy.txt '.'TesterFolder-I_Have_a_Dream.txt'.'TesterFolder-tester-i_have_a_dream - Copy (2).txt'.'Tes terfolder-Tester-i_have_a_dream - copy (3).txt'.'TesterFolder-WordCount_Basic.py'])
In [6]: os.mkdir("aiyc")
---------------------------------------------------------------------------
FileExistsError Traceback (most recent call last)
<ipython-input-6-53b10652ea17> in <module>
----> 1 os.mkdir("aiyc")
FileExistsError: [WinError 183] Cannot create a file that already exists. :'aiyc'
In [7]: os.mkdir("aiyc/blog/PythonCourse")
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-7-50d273e0ff25> in <module>
----> 1 os.mkdir("aiyc/blog/PythonCourse")
FileNotFoundError: [WinError 3] The system could not find the specified path. :'aiyc/blog/PythonCourse'
In [8]: os.makedirs("aiyc/blog/PythonCourse")
In [9] :for path in os.walk('. ') :... :print(path) ... : ('. '['aiyc'.'Tester2Folder'.'TesterFolder'], ['OS-alexSmith_2021 - copy (2).txt'.'OS-alexSmith_2021 - copy (3).txt'.'OS-AlexSmith_2021 - 副本.txt'.'OS-A
lexSmith_2021.txt'.'OS-i_have_A_dream - copy (2).txt'.'OS-i_have_a_dream - copy.txt'.'OS-I_Have_a_Dream.txt'.'OS-wordcount_basic - copy (2).py'.'OS-wordco unt_Basic - copy.py'.'OS-WordCount_Basic.py'.'OS_Page.py'])
('.\\aiyc'['blog'], [])
('.\\aiyc\\blog'['PythonCourse'], [])
('.\\aiyc\\blog\\PythonCourse', [], [])
('.\\Tester2Folder'['Tester2Folder_test'], ['Tester2Folder-AlexSmith_2021 - Copy (2).txt'.'Tester2Folder-AlexSmith_2021 - Copy (3).txt'.'Tester2Folder-Alex Smith_2021 - Copy (4).txt'.'Tester2Folder- alexSmith_2021-copy.txt '.'Tester2Folder-AlexSmith_2021.txt'.'Tetser2-WordCount_Basic.py'])
('.\\Tester2Folder\\Tester2Folder_test', [], [])
('.\\TesterFolder', [], ['TesterFolder-I_Have_a_Dream - copy.txt '.'TesterFolder-I_Have_a_Dream.txt'.'TesterFolder-tester-i_have_a_dream - Copy (2).txt'.'Tes terfolder-Tester-i_have_a_dream - copy (3).txt'.'TesterFolder-WordCount_Basic.py'])
In [10] :Copy the code
2.6 OS. The remove ()
Used to delete files, raising IsADirectoryError if the specified path is a directory instead of a file. Directories should be deleted using the os.rmdir() function.
Similarly, corresponding to os.makedirs(), the delete path operation os.rmdir() also has a recursive delete function os.removedirs(), which attempts to delete the specified path level by level, starting with the lowest directory. It’s almost a reverse of os.makedirs(); Stop as soon as you encounter a non-empty directory.
In [10]: os.removedirs("aiyc/blog/PythonCourse/") I manually created a file in the blog folder
In [11]: os.removedirs("aiyc/blog")
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-12-271d0185833e> in <module>
----> 1 os.removedirs("aiyc/blog")
c:\users\clela\appdata\local\programs\python\python38\lib\os.py in removedirs(name)
239
240 """
--> 241 rmdir(name)
242 head, tail = path.split(name)
243 if not tail:
OSError: [WinError 145] 目录不是空的。: 'aiyc/blog'
Copy the code
2.7 OS. Rename ()
Rename (SRC, DST). Rename the file or path pointed to by SRC to the name specified by DST.
Note that this function can also cut and paste files or paths if the specified destination path is in another directory.
But whether you rename it in place or “cut and paste”, the intermediate path must exist or FileNotFoundError will be raised. If the destination path already exists, An FileExistsError exception is raised on Windows. On Linux, if the destination path is empty and the user permission permits, the original path will be silently overwritten. Otherwise, an OSError exception will be raised.
Like the previous two functions, this one has a corresponding recursive version of os.renames(), which creates missing intermediate paths.
Note that in both cases, if the function executes successfully, the os.removedir() function is called to recursively remove the most subordinate directory of the source path.
Look not to understand? It’s okay. I can’t read it either! Ha ha ha ha ha ha ha! But let me give you a little example.
We now use this path: C:\Users\clela\Desktop\aiyc, which contains the following files:
The following information is displayed:
In [1]: pwd
Out[1] :'C:\\Users\\clela\\Desktop\\aiyc'
In [2]: ls volume in drive C is the directory of OS volume with serial number 0AED-8BC3 C:\Users\clela\Desktop\aiyc2021/ 09 /27 21:08 <DIR> .
2021/ 09 /27 21:08 <DIR> ..
2021/ 09 /27 19: 052.183.368 1.2Dinosaur Land PPTX202108 /30 09:11 772, 010,1.2Dinosaur Land. Sb32A file2.955.378byte2A directory161.160.978.432Available bytes In [3] :Copy the code
Now, let’s do a wave. First, change the file name:
Rename:
- Original file path:
C:\ Users\ clela\ Desktop\ aiyc\ 1.2 Dinosaur paradise. PPTXCopy the code
- Rename the file and point to the same path:
C:\\Users\\clela\\Desktop\\aiyc\\1.2I'll rename it.pptxCopy the code
- The code used is as follows:
In [1]: pwd
Out[1] :'C:\\Users\\clela\\Desktop\\aiyc'
In [2] :import os
In [3]: path_one = "C:\ Users\ clela\ Desktop\ aiyc\ 1.2 Dinosaur Paradise. PPTX"
In [4]: path_two = "C:\ Users\ clela\ Desktop\ aiyc\ 1.2 Rename.pptx"
In [5]: os.rename(path_one, path_two)
Copy the code
We can open it up and see that the name has been changed successfully.
In [6]: ls volume in drive C is the directory of OS volume with serial number 0AED-8BC3 C:\Users\clela\Desktop\aiyc2021/ 09 /28 15:41 <DIR> .
2021/ 09 /28 15:41 <DIR> ..
202108 /30 09:11 772, 010,1.2Dinosaur Land. Sb32021/ 09 /27 19: 052.183.368 1.2I'll rename it.pptx2A file2.955.378byte2A directory159.386.759.168Available bytes In [7] :Copy the code
What about moving files?
Moving files:
- Original file path:
C:\ Users\ clela\ Desktop\ aiyc\ 1.2 Rename.pptxCopy the code
- A new path:
C:\ Users\ clela\ Desktop\ aiyc_book\ 1.2 rename.pptxCopy the code
- Code used:
In [7]: path_one = "C:\ Users\ clela\ Desktop\ aiyc\ 1.2 Rename.pptx"
In [8]: path_two = "C: \ \ Users \ \ clela \ \ Desktop \ \ aiyc_book \ \ 1.2 rename. PPTX." "
In [9] : os.rename(path_one, path_two) --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-9-2390249a0f17> in <module>
----> 1 os.rename(path_one, path_two)
FileNotFoundError: [WinError 3] The system could not find the specified path. :'C:\ Users\ clela\ Desktop\ aiyc\ 1.2 Rename.pptx' -> 'C: \ \ Users \ \ clela \ \ Desktop \ \ aiyc_book \ \ 1.2 rename. PPTX'
Copy the code
The above code cannot be used because the current aiyc_book folder does not exist.
Of course, you can create folders manually and run the code above. But that defeats the purpose of office automation, so we can use the os.renames() function instead.
In [12]: os.renames(path_one, path_two)
Copy the code
2.8 OS. Getcwd ()
“Getcwd” is actually short for “get the current working directory”, as the name implies, so this function is used to “get the current working path”. During the program running, no matter where the program is physically in the actual storage space, the “current working path” can be considered as the path where the program is located. For related operations, such as Relative path and Module import in the same directory, the current Working Path prevails.
In an interactive environment, the return is the open position of the interactive terminal; In Python files, the location of the file is returned.
On Windows, the following output is displayed:
In [13]: os.getcwd()
Out[13] :'C:\\Users\\clela\\Desktop\\aiyc'
Copy the code
The output for Linux is:
In [1] :import os
In [2]: os.getcwd()
Out[2] :'/ home/aiyc/desktop'
Copy the code
2.9 OS. The chdir ()
“Chdir” is actually short for “change the directory”, so os.chdir() is actually used to switch the current working path to the specified path. Where “specify path” needs to be passed to the function os.chdir() as an argument, which can be a text or byte string, a file descriptor, or a generalized path-like object. If the specified path does not exist, FileNotFoundError is raised.
On Windows, the effect of calling this function is:
In [13]: os.getcwd()
Out[13] :'C:\\Users\\clela\\Desktop\\aiyc'
In [14]: os.chdir("C:\\Users\\clela\\Desktop")
In [15]: pwd
Out[15] :'C:\\Users\\clela\\Desktop'
In [16]: os.getcwd()
Out[16] :'C:\\Users\\clela\\Desktop'
Copy the code
On Linux, it looks like this:
In [1]: import OS In [2]: os.getcwd() Out[2]: '/home/aiyc/ desktop 'In [3]: os.chdir("/home/aiyc") In [4]: os.getcwd() Out[4]: '/home/aiyc' In [5]: os.chdir(".." ) # you can also specify ".." In [6]: os.getcwd() Out[6]: '/home'Copy the code
With this function, file directory, speaking, reading and writing and calling module will become very convenient, many times also don’t have to repeatedly to the same files in the directory, copy and paste operation between script can completely in ZhongJun, for other directory file in a directory to complete the operation, is the so-called “strategizing, runoff away”.
For example, you can directly access the contents of files in the parent directory by switching the current working directory to the parent directory:
In [9] :import os
In [10]: os.getcwd()
Out[10] :'D:\\Curriculum- Development \\ Office automation \\Coder\\02- File manipulation \\OS_Module_Code\\TesterFolder'
In [11]: os.chdir("..")
In [12]: os.getcwd()
Out[12] :'D:\\Curriculum- Development \\ Office automation \\Coder\ 02- File operation \\OS_Module_Code'
In [13] :with open("hello_aiyc.txt"."r", encoding="utf-8") asf: ... :print(f.read()) ... : Welcome to aiyc.com and learn about Python.14]: os.listdir()
Out[14] : ['aiyc'.'hello_aiyc.txt'.'OS-alexSmith_2021 - copy (2).txt'.'OS-alexSmith_2021 - copy (3).txt'.'OS-AlexSmith_2021 - 副本.txt'.'OS-AlexSmith_2021.txt'.'OS-i_have_A_dream - copy (2).txt'.'OS-i_have_a_dream - copy.txt'.'OS-I_Have_a_Dream.txt'.'OS-wordcount_basic - copy (2).py'.'os-wordcount_basic - copy.py'.'OS-WordCount_Basic.py'.'OS_Page.py'.'Tester2Folder'.'TesterFolder'.'__pycache__']
Copy the code
3. OS. Path module
In fact, the OS module imports this module from another module based on the system type, not directly implemented by the OS module. For example, if the value of os.name is nt, run import ntPATH as path in the OS module. If the os.name value is POSIX, posixpath is imported.
One important feature to note when using this module is that the functions in os.path are basically pure string operations. In other words, the argument passed to the module’s function doesn’t even need to be a valid path, and the module doesn’t try to access it, but simply processes the string in the generic format for “path.”
Furthermore, the os.path module does all of the things you can do manually using string manipulation. It allows you to do the same things without having to worry about the system, especially file system separators.
3.1 OS. Path. The join ()
This is a very useful function to combine multiple incoming paths into a single path. In effect, several strings passed in are concatenated with system separators to form a new string, so the general usage is to take the first parameter as the parent directory, and then each parameter to the next level of directory to form a new logical path.
But if there is a string in the form of an “absolute path” that is not the first argument to the function, all other arguments before this parameter are discarded and the remaining arguments are combined. More precisely, only the last “absolute path” and the parameters after it are reflected in the returned result.
In [16]: os.path.join("aiyc"."do"."python"."dot"."top")
Out[16] :'aiyc\\do\\python\\dot\\top'
In [17]: os.path.join("aiyc"."do"."C:/"."python"."dot"."top")
Out[17] :'C:/python\\dot\\top'
In [18]: os.path.join("aiyc"."do"."d:/"."python"."dot"."g:/"."top")
Out[18] :'g:/top'
Copy the code
3.2 OS. Path. Abspath ()
Normalize the incoming path, returning a corresponding string in absolute path format.
That is, when an incoming path matches the format of “absolute path,” the function simply replaces the path separator with the character appropriate to the current system, does nothing else, and returns the result. Absolute path format refers to the format of a letter followed by a colon followed by a delimiter and a string sequence:
In [23]: os.path.abspath("a:/aiyc/do/python") # I don't have drive A on my system
Out[23] :'a:\\aiyc\\do\\python'
In [24]: os.path.abspath("a:/aiyc/do//python")
Out[24] :'a:\\aiyc\\do\\python'
In [25]: os.path.abspath("a:/aiyc/do//////python")
Out[25] :'a:\\aiyc\\do\\python'
Copy the code
When the specified path does not conform to the above format, the function automatically takes the current working path and combines it with the passed arguments into a new path string using the os.path.join() function. The following is an example:
In [28]: os.getcwd()
Out[28] :'D:\\Curriculum- Development \\ Office automation \\Coder\ 02- File operation \\OS_Module_Code'
In [29]: os.path.abspath("Python_online/aiyc")
Out[29] :'D:\\Curriculum- Development \\ Office automation \\Coder\\02- File operation \\OS_Module_Code\\Python_online\\aiyc'
Copy the code
3.3 OS. Path. The basename ()
This function returns the “base name” of the passed path, which is the most subordinate directory of the passed path.
In [31]: os.path.basename("D:\\Curriculum-development\\ aiyc_Lesson \\Coder\ 02- File operation \\OS_Module_Code") # MY system does not have such a path either. You can see that the os.path.basename() page is purely string processing
Out[31] :'OS_Module_Code'
Copy the code
The important thing to note about this function is that the “base name” returned is actually a substring after the last delimiter of the path passed in, that is, if there is a delimiter after the lowest directory, the result will be an empty string:
In [33]: os.path.basename("D:\\Curriculum-development\\ aiyc_Lesson \\Coder\ 02- File operation \\OS_Module_Code\\")
Out[33] :' '
Copy the code
3.4 OS. The path. The dirname ()
The reverse of the previous function returns the entire string before the last delimiter:
In [35]: os.path.dirname("D:\\Curriculum-development\\ aiyc_Lesson \\Coder\ 02- File operation \\OS_Module_Code")
Out[35] :'D:\\Curriculum-development\\ aiyc_Lesson \\Coder\ 02- File Operation '
In [36]: os.path.dirname("D:\\Curriculum-development\\ aiyc_Lesson \\Coder\ 02- File operation \\OS_Module_Code\\")
Out[36] :'D:\\Curriculum-development\\ aiyc_Lesson \\Coder\ 02- File operation \\OS_Module_Code'
Copy the code
3.5 OS. Path. The split ()
In fact, the first two functions are the younger brother, this function is the eldest.
The os.path.split() function splits the incoming path into two strings bounded by the last delimiter and returns them as tuples.
The return value of the first two functions os.path.dirname() and os.path.basename() is the first and second element of the return value of os.path.split(), respectively.
Even the concrete implementation of both is quite real:
Signature: os.path.dirname(p)
Source:
def dirname(p) :
"""Returns the directory component of a pathname"""
return split(p)[0]
File: c:\users\clela\appdata\local\programs\python\python38\lib\ntpath.py
Type: function
Signature: os.path.basename(p)
Source:
def basename(p) :
"""Returns the final component of a pathname"""
return split(p)[1]
File: c:\users\clela\appdata\local\programs\python\python38\lib\ntpath.py
Type: function
Copy the code
The os.path.join() function can combine them again to get the original path.
3.6 OS.path.exists () Whether a path exists
This function is used to determine whether the location to which the path points exists. Return True if it exists, False if it does not:
In [41]: os.path.exists(".")
Out[41] :True
In [42]: os.path.exists("D:\\Curriculum-development\\aiyc_lesson\\Coder\ 02- File operation \\OS_Module_Cod") The path does not exist
Out[42] :False
In [43]: os.path.exists("D:\\Curriculum-development\\")
Out[43] :True
Copy the code
The general usage is to use this function to check whether the corresponding file exists before writing to avoid creating a file repeatedly. If not, create a new file. If yes, add new content after the file content.
3.7 OS. Path. Isabs ()
This function determines whether the passed path is absolute and returns True if it is, and False otherwise. Of course, just testing the format also does not carry out any verification of its validity:
In [46]: os.path.isabs(".")
Out[46] :False
In [47]: os.path.isabs("D:\\Curriculum-development")
Out[47] :True
Copy the code
3.8 OS. Path. Isfile () and OS. Path. Isdir ()
These two functions determine whether the passed path is a file or a path, respectively. Note that the path is checked for validity and will continue to return False if it is invalid.
In [54] :# invalid path
In [55]: os.path.isfile("a:/aiycpython")
Out[55] :False
In [56] :# valid path
In [57]: os.path.isfile("OS-AlexSmith_2021.txt")
Out[57] :True
In [58] :# invalid path
In [59]: os.path.isdir("D:\\Curriculum-development\\aiyc")
Out[59] :False
In [60] :# valid path
In [61]: os.path.isdir("D:\\Curriculum-development")
Out[61] :True
Copy the code
4. To summarize
This paper introduces in detail some common properties and functions in the OS module that interact with the operating system, which can basically cover the initial learning and use. With these features, we can now write some useful scripts.
In addition to the functions introduced in this article, the OS module has many more complex functions, but most of them are temporarily unavailable to us, and will be further explained in the future.
Official account: AI Yue Chuang