# Python OS module details

Time：2021-12-5

Hello, this is yuechuang.

If we want to operate files and directories, we can enter various commands provided by the operating system under the command line. Such as dir, CP and other commands.

What if you want to perform the operations of these directories and files in a python program?

< font color = “red” > in fact, the commands provided by the operating system simply call the interface functions provided by the operating system. The built-in OS module of Python can also directly call the interface functions provided by the operating system</ font>

## 1. Introduction

osIt is the abbreviation of “operating system”. As the name suggests,osThe module provides interfaces for various Python programs to interact with the operating system. through the use ofosModule, on the one hand, can easily interact with the operating system, on the other hand, page can greatly enhance the portability of code. If there is an error in the relevant function in the module, an error message will be thrownOSErrorException or its subclass exception.

be careful:This module provides a convenient way to use the functions related to the operating system. If it is a read-write file, it is recommended to use the built-in functionopen()； For path related operations, it is recommended to useosSub module ofos.path； If you want to read multiple files line by line, it is recommended to usefileinputmodular; To create a temporary file or path, it is recommended to usetempfilemodular; For more advanced file and path operations, you should useshutilmodular.

Of course, useosModule can write operating system independent code, which does not meanosSome system specific extensions cannot be invoked, but one thing to keep in mind: once you do this, it will be extremely difficultCompromise code portability

In addition, importosBe careful when using the moduleNoIn order to save trouble in calling graphosModule unpacking and importing, i.e. do not use:

 from os import *

To importosmodular; otherwiseos.open()Built in functions will be overriddenopen(), resulting in unexpected errors.

## 2. Common functions

be carefulosMost functions in the module that accept paths as parameters can also accept “file descriptors” as parameters.

File descriptor:File descriptor, abbreviated as FD in Python documents, is an integer bound to an open file object, which can be understood as the number of the file in the system.

### 2.1 os.name

This attribute broadly indicates the environment in which Python is currently running. In fact, it is the name of the relevant module of the imported operating system. This name also determines theWhat features are available, which are not implemented accordingly.

Currently, there are three valid names:posixntjava

Of which:

• posixIt is the abbreviation of portable operating system interface of UNIX. Both Linux and Mac OS will return this value;
• ntThe full name should be “Microsoft Windows NT”, which can be roughly equivalent to the windows operating system, so this value will be returned in the windows environment;
• javaIs the return value in the Java virtual machine environment.

In short: if it is POSIX, it means that the system is Linux, UNIX or Mac OS X. if it is nt, it means windows system.

Therefore, execute the following code on my computer (win10) and the return value isnt

In [1]: import os

In [2]: os.name
Out[2]: 'nt'

On WSL (Windows subsystem Linux, Linux subsystem under Windows), the result is:

In [2]: import os

In [3]: os.name
Out[3]: 'posix'

seesysIn the modulesys.platformProperty can get more detailed information about the running platform, which will not be repeated here

Windows10：

In [4]: sys.platform
Out[4]: 'win32'

Linux：

In [5]: sys.platform
Out[5]: 'linux'

PS：To get detailed system information, you can calluname()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')

be carefulThe uname() function is not available on windows, that is, some functions of the OS module are related to the operating system.

### 2.2 environment variable os.environ

os.environProperty can return environment related information, mainly various environment variables. The return value is a mapping (similar to dictionary type), and the specific value is the first importosSnapshot of the module; For each key value pair, the key is the name of the environment variable, and the value is the corresponding value of the environment variable. Import for the first timeosAfter the module, unless directly modifiedos.environOtherwise, the value of the property will not change.

All environment variables defined in the operating system are saved in os.environ, which 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',...}

To get the value of an environment variable, you can callos.environ.get('key')For example, if the key is “HomePath” (windows, Linux, home), the corresponding value is the path to the user’s home directory. Under windows, its value is:

In [9]: os.environ["HOMEPATH"]
Out[9]: '\\Users\\clela'

Under Linux, its value is:

In [17]: os.environ["HOME"]
Out[17]: '/home/aiyc'

### 2.3 os.walk()

This function needs to pass in a path astopParameter, the function is totopTo walk in the directory tree of the root node, generate a directory for each directory in the tree(dirpath, dirnames, filenames)A triple of three terms.

Of which:

• dirpathIs a string indicating the directory path,
• dirnamesIt’s adirpathSubdirectory name (remove)“.”and“..”）ComposedlistfilenamesBydirpathA list of all non directory file names under.
• Note that these names do not contain the path itself. GetdirpathNext file or path fromtopThe full path to the beginning of the directory, which needs to be usedos.path.join(dirpath, name)

Note that the final result returned is an iterator that we can useforStatement to get each item of the iterator one by one:

for item in os.walk("."):
print(item)
('.', ['do'], ['go_go_go.txt'])
('.\\do', ['IAmDirectory', 'python'], [])
('.\\do\\IAmDirectory', [], [])
('.\\do\\python', [], ['hello_justdopython.txt'])

Example 2:

import os

for pt in os.walk("."):
print(pt)
('.', ['tester2folder ',' testerfolder '], ['os alexsmith_2021 - copy (2). TXT', 'OS alexsmith_2021 - copy (3). TXT', 'OS alexsmith_2021 - copy. 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', ['tester2folder_test '], ['tester2folder alexsmith_2021 - copy (2). TXT', 'tester2folder alexsmith_2021 - copy (3). TXT', 'tester2folder alexsmith_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 ',' testerfolder-tester-i_have_a_dream - copy (3). TXT ',' testerfolder wordcount_basic. Py '])

### 2.4 os.listdir()

listdirNamelylist directories, list all paths (and files) in the (current) directory. The function has a parameter to specify the path to list subdirectories. The default is., the current path.

The return value of the function is a list in which each element is a string, including each path name and file name.

It is usually very 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 described later
if os.path.isfile(directory):
filelists.append(directory)
return filelists

The return value of this function is the name list of all files in the current directory instead of folders.

### 2.5 os.mkdir()

mkdir, i.emake directory, the use isCreate a new path。 You need to pass in a classpath parameter to specify the location and name of the new path. If the specified path already exists, it will be thrownFileExistsErrorAbnormal.

This function can only create a new level path under the existing path, otherwise (that is, create a new level path) will be thrownFileNotFoundErrorAbnormal.

Accordingly, in the scenario where a multi-level path needs to be created, you can useos.makedirs()To complete the task. functionos.makedirs()Recursive creation is performed. If necessary, intermediate paths passing through the specified path will be created respectively until the end path is finally created“Leaf path”。

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 when it 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 cannot 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")

Example 2:

In [1]: import os

In [2]: os.getcwd()
Out [2]:'d: \ \ curriculum development \ \ office automation using Python \ \ 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 - copy. 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 Alex Smith_ 2021 - copy. TXT ','tester2folder Alex Smith_ 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 - copy. 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 Alex Smith_ 2021 - copy. TXT ','tester2folder Alex Smith_ 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 when it 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 cannot 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 - copy. 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 Alex Smith_ 2021 - copy. TXT ','tester2folder Alex Smith_ 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]:

### 2.6 os.remove()

Used to delete files, if the specified path is a directory rather than a file, it will be thrownIsADirectoryErrorAbnormal. Delete directory should useos.rmdir()Function.

Similarly, corresponding toos.makedirs(), delete path operationos.rmdir()There is also a recursive deletion functionos.removedirs(), this function will try to delete the specified path level by level from the lowest level directory, almost oneos.makedirs()Inverse process of; Stop once a non empty directory is encountered.

In [10]: OS. Removediers ("aiyc / blog / Python course /) # 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)
243     if not tail:

Oserror: [winerror 145] directory is not empty.: ' aiyc/blog'

### 2.7 os.rename()

This function renames a file or path. The general calling format isos.rename(src, dst), coming soonsrcRename the file or path todstSpecifies the name of the.

be careful,If the specified destination path is in another directory, this function can also realize the of files or pathsCut and pasteFunction.

However, whether renaming directly in place or “cutting and pasting”, the intermediate path must exist, otherwise it will be thrownFileNotFoundErrorAbnormal. If the target path already exists, it will be thrown under windowsFileExistsErrorAbnormal; Under Linux, if the target path is empty and the user permission allows, the original path will be silently overwritten, otherwise thrownOSErrorAbnormal,

Like the previous two functions, this function also has a corresponding recursive versionos.renames(), you can create missing intermediate paths.

Note that in both cases, if the function is executed successfully, it will be calledos.removedir()Function to recursively delete the lowest level directory of the source path.

Don’t you understand? It’s okay, I can’t understand! Ha ha ha ha ha ha! But let me give you a small example to understand!

We now use this path:C:\Users\clela\Desktop\aiyc, there are the following files in this path:

The command line is displayed as follows:

In [1]: pwd
Out[1]: 'C:\\Users\\clela\\Desktop\\aiyc'

In [2]: ls
The volume in drive C is an OS
The serial number of the volume is 0aed-8bc3

C: Directory of \ users \ clela \ desktop \ aiyc

2021/09/27  21:08    <DIR>          .
2021/09/27  21:08    <DIR>          ..
2021 / 09 / 27 19:05 2183368 1.2 dinosaur paradise.pptx
2021 / 08 / 30 09:11 772010 1.2 dinosaur paradise.sb3
2 files 2955378 bytes
2 directories 161160978432 bytes available

In [3]:

Next, let’s operate a wave. In the first wave, modify the file name:

Rename:

1. Original file path:
C: \ \ users \ \ clela \ \ desktop \ \ aiyc \ \ 1.2 dinosaur paradise.pptx
1. Rename the file and point to the same path:
C: \ \ users \ \ clela \ \ desktop \ \ aiyc \ \ 1.2 rename. Pptx
1. The codes used are 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)

We can open it and see that the name has been successfully modified.

In [6]: ls
The volume in drive C is an OS
The serial number of the volume is 0aed-8bc3

C: Directory of \ users \ clela \ desktop \ aiyc

2021/09/28  15:41    <DIR>          .
2021/09/28  15:41    <DIR>          ..
2021 / 08 / 30 09:11 772010 1.2 dinosaur paradise.sb3
2021 / 09 / 27 19:05 2183368 1.2 rename.pptx
2 files 2955378 bytes
2 directories 159386759168 available bytes

In [7]:

What about the mobile files mentioned above?

Move files:

1. Original file path:
C: \ \ users \ \ clela \ \ desktop \ \ aiyc \ \ 1.2 rename. Pptx
1. New path:
C:\\Users\\clela\\Desktop\\aiyc_ Book \ \ 1.2 rename. Pptx
1. 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 cannot find the specified path.: ' C: \ \ users \ \ clela \ \ desktop \ \ aiyc \ \ 1.2 rename
Name. Pptx '- >' C: \ \ users \ \ clela \ \ desktop \ \ aiyc_ Book \ \ 1.2 rename. Pptx '

The above code cannot be used because the currentaiyc_bookThis folder does not exist.

Of course, you can manually create a folder and run the above code. But this obviously goes against the original intention of automated office, so we can use itos.renames()Function.

In [12]: os.renames(path_one, path_two)

### 2.8 os.getcwd()

“Getcwd” is actually short for “get the current working directory”. As the name suggests, that is, the function is to “get the current working path”. In the process of program running, no matter where the program is physically in the actual storage space, “current working path” can be regarded as the path where the program is located; Related operations such as “relative path” and “module import under the same directory” are subject to “current working path”.

In the interactive environment, what is returned is the open position of the interactive terminal; In Python files, the location of the file is returned.

Under windows, the following output will be displayed:

In [13]: os.getcwd()
Out[13]: 'C:\\Users\\clela\\Desktop\\aiyc'

The output under Linux is:

In [1]: import os

In [2]: os.getcwd()
Out [2]: '/ home / aiyc / desktop'

### 2.9 os.chdir()

“Chdir” is actually short for “change the directory”, soos.chdir()The utility of is actually to switch the current working path to the specified path. Where “specify path” needs to be passed into the function as a parameteros.chdir(), the parameter can be either a text or byte string, a file descriptor, or a generalized path like object. Thrown if the specified path does not existFileNotFoundErrorAbnormal.

Under 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'

The effect under Linux is:

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 the parameter as ".." to switch to the parent directory

In [6]: os.getcwd()
Out[6]: '/home'

With this function, it will be very convenient to read and write files across directories and call modules. In many cases, it is no longer necessary to repeatedly copy and paste the same file between directories. The script can sit in the middle army and complete the operation of other directory files in one directory, which is the so-called“In devising strategies, we will win thousands of miles away”Also.

For example, you can directly access the file contents of 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 using Python \ \ coder \ \ 02 - file operation \ \ OS_ Module_ Code\\TesterFolder'

In [11]: os.chdir("..")

In [12]: os.getcwd()
Out [12]:'d: \ \ curriculum development \ \ office automation using Python \ \ coder \ \ 02 - file operation \ \ OS_ Module_ Code'

In [13]: with open("hello_aiyc.txt", "r", encoding="utf-8") as f:
...:
Welcome to aiyc.com to learn Python technology~

In [14]: os.listdir()
Out[14]:
['aiyc',
'hello_aiyc.txt',
'OS-AlexSmith_ 2021 - copy (2). TXT ',
'OS-AlexSmith_ 2021 - copy (3). TXT ',
'OS-AlexSmith_ 2021 - copy. 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__']

## 3. Os.path module

In fact, this module isosModules are imported from another module according to the system type and are not directly imported by theosModule implementation, such asos.nameValue isnt, thenosExecute in moduleimport ntpath as path； Ifos.nameValue isposix, importposixpath

There is a very important feature to note when using this module:os.pathThe functions in are basically pure string operations. In other words, the parameter passed into the module function does not even need to be a valid path, and the module will not attempt to access the path, but only process the string according to the general format of “path”.

Further,os.pathWe can manually implement the functions of the module by using string operation. The function of the module is that we do not have to consider the specific system when implementing the same functions, especially the problem of paying too much attention to the file system separator.

### 3.1 os.path.join()

This is a very practical function, which can combine multiple incoming paths into one path. In fact, several incoming strings are connected with the system separator to form a new string. Therefore, the general usage is to take the first parameter as the parent directory, and then each parameter even the next level directory, so as to form a new logical path.

However, if there is a string in “absolute path” format in the incoming path and this string is not the first parameter of the function, all other parameters before this parameter will be discarded and the remaining parameters will be combined. More precisely, only the last “absolute path” and its subsequent parameters will be reflected in the returned results.

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'

### 3.2 os.path.abspath()

Normalize the incoming path and return a string in the corresponding absolute path format.

That is, when the incoming path conforms to the format of “absolute path”, the function only replaces the path separator with a character suitable for the current system without any other operation, and returns the result. The so-called “format of absolute path” actually refers to the format of a letter plus colon, followed by separator and string sequence:

In [23]: OS. Path. Abspath ("A: / aiyc / do / Python") # I don't have a disk in 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'

When the specified path does not conform to the above format, the function will automatically obtain the current working path and useos.path.join()The function combines it with the passed in parameters to form a new path string. Examples are as follows:

In [28]: os.getcwd()
Out [28]:'d: \ \ curriculum development \ \ office automation using Python \ \ coder \ \ 02 - file operation \ \ OS_ Module_ Code'

In [29]: os.path.abspath("Python_online/aiyc")
Out [29]:'d: \ \ curriculum development \ \ office automation using Python \ \ coder \ \ 02 - file operation \ \ OS_ Module_ Code\\Python_ online\\aiyc'

### 3.3 os.path.basename()

This function returns the of the incoming path“Base name”, the lowest level directory of the incoming path.

In [31]: os.path.basename ("D: \ \ curriculum development \ \ aiyc_lesson \ \ coder \ \ 02 file operation \ \ os_module_code") # there is no such path in my system. It can be seen that the OS. Path. Basename () page only performs string processing
Out[31]: 'OS_Module_Code'

One thing to note about the whole function is that the returned “base name” is actually a substring after the last separator of the incoming path, that is, if there is a separator after the lowest level directory, the result will be an empty string:

In [33]: os.path.basename ("D: \ \ curriculum development \ \ aiyc_less \ \ code \ \ 02 - file operation \ \ os_module_code \ \")
Out[33]: ''

### 3.4 os.path.dirname()

Contrary to the previous function, it returns the entire string before the last delimiter:

In [35]: os.path.dirname ("D: \ \ curriculum development \ \ aiyc_less \ \ 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_less \ \ coder \ \ 02 - file operation \ \ os_module_code \ \")
Out[36]: 'D:\\Curriculum-development\\aiyc_ Lesson \ \ coder \ \ 02 - file operation \ \ OS_ Module_ Code'

### 3.5 os.path.split()

Ha ha, in fact, the first two functions are brothers, and this function is the boss.

functionos.path.split()The function of is to divide the incoming path into two strings bounded by the last separator, and package it into a meta group to return;

First two functionsos.path.dirname()andos.path.basename()The return values of are functionsos.path.split()The first and second elements of the return value.

Even the concrete realization of the two is very 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

adoptos.path.join()Function can combine them to get the original path.

### 3.6 does the OS. Path. Exists() path exist

This function is used to determine whether the location pointed by the path exists. If it exists, returnTrue, if it does not exist, returnFalse

In [41]: os.path.exists(".")
Out[41]: True

In [42]: OS. Path. Exists ("D: \ \ curriculum development \ \ aiyc_less \ \ coder \ \ 02 - file operation \ \ os_module_cod") # nonexistent path
Out[42]: False

In [43]: os.path.exists("D:\\Curriculum-development\\")
Out[43]: True

The general usage is to use this function to check whether the corresponding file exists before writing in the scenario where some data needs to be persisted and saved. If it does not exist, create a new one. If it does exist, add new content after the file content.

### 3.7 os.path.isabs()

This function determines whether the incoming path is an absolute path. If so, it returnsTrue, otherwise returnFalse。 Of course, only the detection format will not be verified for its effectiveness:

In [46]: os.path.isabs(".")
Out[46]: False

In [47]: os.path.isabs("D:\\Curriculum-development")
Out[47]: True

### 3.8 OS. Path. Isfile() and OS. Path. Isdir()

These two functions respectively judge whether the incoming path is a file or path. Note that the validity of the path will be verified here. If it is invalid, the path will continue to returnFalse

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

## 4. Summary

This paper introduces the interaction with the operating system in detailosSome common attributes and functions in the module can basically cover the learning and use of the primary level. With these functions, we can write some practical scripts.

In addition to the functions described in the article,osThere are many more complex functions in the module, but most of them are temporarily unavailable to us. We will explain them further in the future.

AI yuechuang · launched tutorial classes, including “Python language tutorial class, C + + tutorial class, algorithm / data structure tutorial class, children’s programming, pyGame game game development”, all of which are one-to-one teaching: one-to-one counseling + one-to-one Q & A + homework assignment + project practice, etc. QQ, wechat online, respond at any time! V：Jiabcdefh

## The real problem of Alibaba IOS algorithm can’t hang up this time

More and more IOS developers continue to enter the peak of job hopping in 2020 Three main trends of interview in 2020: IOS bottom layer, algorithm, data structure and audio and video development Occupied the main battlefield. Data structure and algorithm interview, especially figure, has become the main reason for the failure of most first-line […]