Python os module high-frequency function (to be continued)


>>> import os
>>> os.environ
environ({'CLUTTER_IM_MODULE': 'fcitx', 'COLORTERM': 'truecolor', 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=/run/user/1000/bus', 'DESKTOP_SESSION': 'deepin', 'DISPLAY': ':0', 'D_DISABLE_RT_SCREEN_SCALE': '1', 'D_DXCB_FORCE_OVERRIDE_HIDPI': '1', 'GDMSESSION': 'deepin', 'GIO_LAUNCHED_DESKTOP_FILE': '/usr/share/applications/deepin-terminal.desktop', 'VIRTUALENVWRAPPER_WORKON_CD': '1', 'VIRTUALENVWRAPPER_SCRIPT': '/home/ljk/.local/bin/', 'WORKON_HOME': '/home/ljk/.virtualenvs', 'VIRTUALENVWRAPPER_HOOK_DIR': '/home/ljk/.virtualenvs', 'VIRTUAL_ENV': '/home/ljk/.virtualenvs/ymir', 'PS1': '(ymir) %(?:%{\x1b[01;32m%}➜ :%{\x1b[01;31m%}➜ ) %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)', '_': '/home/ljk/.virtualenvs/ymir/bin/python'})
>>> os.environ.get("HOME")


The os.walk() method is used to output the file names in the directory by walking in the directory tree. All directories, including nested subdirectories, will be output with file names.

The syntax of the walk() method is as follows:

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
  • top -- is the address of the directory you want to traverse, and returns a triple (root,dirs,files).
  1. root refers to the address of the folder currently being traversed
  2. dirs is a list whose contents are the names of all directories in the folder (excluding subdirectories)
  3. files is also a list, the content is all files in the folder (excluding subdirectories)
  • topdown -- optional, if it is True, the top directory will be traversed first, otherwise the subdirectories of top will be traversed first (default is enabled). If the topdown parameter is True, walk will traverse the top folder and every subdirectory in the top folder.

  • onerror -- optional, requires a callable object, which will be called when walk expects an exception.

followlinks -- Optional, if it is True, it will traverse the directory actually pointed to by the shortcut in the directory (soft link symbolic link under linux) (default is off), if it is False, it will traverse the subdirectory of top first.

(ymir) ➜  zip_demo tree .
├── gt
│   ├── dd.txt
│   ├── hello.txt
│   └── one.txt
├── images
│   └── two.txt
In [3]: for dirpath, dirnames, filenames in os.walk("."):
   ...:     print(f"{dirpath}---{dirnames}---{filenames}")
.---['images', 'gt']---['']
./gt---[]---['dd.txt', 'hello.txt', 'one.txt']


The os.rename() method is used to rename a file or directory from src to dst, if dst is an existing directory, OSError will be thrown.

os.rename(src, dst)

Parameter Description:

  • src -- the file or directory name to modify
  • dst -- the modified file or directory name
In [4]: ls
gt/  images/

In [5]: os.rename("", "")

In [6]: ls
gt/  images/


Used to create a multi-layer directory (single-layer please use os.mkdir)

os.makedirs(name, mode=0o777, exist_ok=False)

Parameter Description:

  • name: the name of the directory you want to create
  • mode: The permission number mode to be set for the directory, the default mode is 0o777 (octal).
  • exist_ok: Whether to trigger an exception when the directory exists. If exist_ok is False (the default), a FileExistsError exception is raised if the target directory already exists; if exist_ok is True, a FileExistsError exception is not raised if the target directory already exists.
In [7]: ls
gt/  images/

In [8]: 

In [8]: os.makedirs("make_dir_test/test", exist_ok=True)

In [9]: ls
gt/  images/  make_dir_test/

In [10]: ls make_dir_test/test/

In [11]: 



Returns the last filename in the path, if the path ends with / or \, then it will return a null value.

In [14]: path =  '/home/ljk/Desktop/zip_demo/'
In [15]: os.path.basename(path)
Out[15]: ''

In [16]: path =  '/home/ljk/Desktop/zip_demo/zipfile_demo'
In [17]: os.path.basename(path)
Out[17]: 'zipfile_demo'

# return null
In [18]: path =  '/home/ljk/Desktop/zip_demo/zipfile_demo/'
In [19]: os.path.basename(path)
Out[19]: ''

In [20]: path =  '/home/ljk/Desktop/zip_demo/zipfile_demo.'
In [21]: os.path.basename(path)
Out[21]: 'zipfile_demo.'


Returns the file path, i.e. removes the file name and returns the directory. Returns empty if the file has only one level of path

In [24]: path =  '/home/ljk/Desktop/zip_demo/'
In [25]: os.path.dirname(path)
Out[25]: '/home/ljk/Desktop/zip_demo'

In [26]: path =  ''
In [27]: os.path.dirname(path)
Out[27]: ''


Split the file name and suffix of the corresponding path, pay attention to the path. After separation, there are two parts: path + suffix

In [26]: path =  ''
In [29]: os.path.splitext(path)
Out[29]: ('zipfile_demo', '.py')

In [30]: path =  '/home/ljk/Desktop/zip_demo/'
In [31]: os.path.splitext(path)
Out[31]: ('/home/ljk/Desktop/zip_demo/zipfile_demo', '.py')

In [32]: path =  '/home/ljk/Desktop/zip_demo/zipfile_demo'
In [33]: os.path.splitext(path)
Out[33]: ('/home/ljk/Desktop/zip_demo/zipfile_demo', '')


The install path separates the path and filename. If the path ends with /, the returned filename is empty

In [34]: path =  '/home/ljk/Desktop/zip_demo/'
In [35]: os.path.split(path)
Out[35]: ('/home/ljk/Desktop/zip_demo', '')

In [36]: path =  '/home/ljk/Desktop/zip_demo/zipfile_demo'
In [37]: os.path.split(path)
Out[37]: ('/home/ljk/Desktop/zip_demo', 'zipfile_demo')

In [38]: path =  '/home/ljk/Desktop/zip_demo/zipfile_demo/'
In [39]: os.path.split(path)
Out[39]: ('/home/ljk/Desktop/zip_demo/zipfile_demo', '')


Processing of paths with path separators:

  1. There are no separators in all paths, and the order of parameters is used by default, and separators are added
In [40]: os.path.join("aa", "bb", "cc")
Out[40]: 'aa/bb/cc'
  1. There are parameters starting with a delimiter, splicing starts from the parameter with a delimiter, and the previous parameters are discarded. Multiple delimiter parameters exist, starting with the last
In [45]: os.path.join("aa", "/bb", "cc")
Out[45]: '/bb/cc'
  1. There are only parameters starting with ./, and they are concatenated according to the order of the parameters.
In [46]: os.path.join("aa", "./bb", "cc")
Out[46]: 'aa/./bb/cc'

In [48]: os.path.join("00", "aa", "./bb", "cc", "./dd")
Out[48]: '00/aa/./bb/cc/./dd'

Tags: Python

Posted by Punk Rock Geek on Tue, 15 Nov 2022 21:52:18 +1030