os of Python standard library

1. Introduction to OS standard library

As the name suggests, OS stands for Operating System, the operating system. The OS standard library is an operating system interface module that provides some functions that facilitate the use of operating system-related functions. The specific installation location can be obtained by importing the os module and viewing the properties os.__file__. When it is necessary to call OS-related functions in Python code to implement business logic or cannot directly use command-line tools, we need to consider importing this module, so it is necessary to conduct in-depth study.

2. OS standard library common functions and attributes

2.1 Files and Directories

2.1.1os.getcwd()

Returns a string representing the current working directory

print("当前工作目录为:{}".format(os.getcwd())) # 返回当前工作目录

insert image description here

2.1.2os.mkdir(path, mode=0o777, *, dir_fd=None)

Create a directory named path with the permission mode mode specified by the number. Some systems will ignore mode. If it is not ignored, then for the Linux system, the permission of the new folder = the permission mode represented by the specified number-the default permission of the umask of the current system user, as shown below

"""
Linux操作系统可通过umask命令获得4个八进制数表示的默认权限,root用户默认是0022,普通用户默认是 0002
第1位数代表文件所具有的特殊权限(SetUID、SetGID、Sticky BIT),后3位数表示表示umask权限值
分别对应所有者、用户组、其他人的权限值,权限与数字对应关系为:r->4,w->2,x->1
"""
exit_code=os.system("umask")

insert image description here

"""
文件夹模式mode赋值为十进制511,等价于八进制0o777
"""
set_mode=511
os.mkdir(path="./cyr",mode=set_mode) # 在当前目录创建名为cyr的文件夹
# 长格式查看新创建的文件夹cyr可知其权限字符串为rwxr-xr-x,等价于转换后的数字权限111101101
!ls -l | grep cyr

insert image description here

umask_value=0o0022 # 当前系统用户八进制表示umask默认权限
new_dir_mode=set_mode-umask_value
print("新建文件夹的权限为:{:b}".format(new_dir_mode))

insert image description here

  • os.rmdir(path, *, dir_fd=None)

    Remove (delete) the directory path . An FileNotFoundErroror OSError.

    os.rmdir("./cyr") # 删除空文件夹成功,无法查到cyr目录
    !ls | grep cyr
    
    os.rmdir("./why") # 删除不存在的文件夹FileNotFoundError报错
    

insert image description here

os.rmdir("./nnunet/") # 删除不为空文件夹OSError报错

insert image description here

  • os.chdir(path)

    Change the current working directory to path

    print("切换前的当前工作目录为:{}".format(os.getcwd())) # 返回当前工作目录
    dst_path="/root" # 目标文件夹
    os.chdir(dst_path) # 将当前工作目录切换为/root
    print("切换后的当前工作目录为:{}".format(os.getcwd())) # 返回当前工作目录
    

insert image description here

  • os.listdir(path='.')

    Returns a list containing the names of all files and directories under the specified path, in any order, except for the special entries '.' and '...'

    dst_path="/code/" # 目标目录
    dirs_ls=os.listdir(path=dst_path) # 获得指定目录下全部文件和文件夹名称列表
    print(dirs_ls)
    

insert image description here

2.2 os.path common path operations

2.2.1os.path.abspath(path)

Returns the absolute path (standardized) of the path path, which is equivalent to string concatenation, and no error will be reported if the path path does not exist

relative_path="tests/test_steps_for_sliding_window_prediction.py" # 路径path存在
print("{}对应的绝对路径为{}".format(relative_path,os.path.abspath(relative_path)))

insert image description here

no_path="tests/none.py" # 路径path不存在
print("{}对应的绝对路径为{}".format(relative_path,os.path.abspath(no_path)))

insert image description here

2.2.2os.path.basename(path)

Returns the basename of the path path

full_pathname="/proc/bus/pci/3a/08.0" # 路径path存在
print("全路径名称对应的文件名为{}".format(os.path.basename(full_pathname)))

insert image description here

no_full_pathname="/demo/none.cpp" # 路径path不存在
print("全路径名称对应的文件名为{}".format(os.path.basename(no_full_pathname)))

insert image description here

2.2.3os.path.dirname(path)

Returns the directory name of the path path

full_pathname="/proc/bus/pci/3a/08.0" # 路径path存在
print("全路径名称对应的目录名称为{}".format(os.path.dirname(full_pathname)))

insert image description here

no_full_pathname="/demo/none.cpp" # 路径path不存在
print("全路径名称对应的目录名称为{}".format(os.path.dirname(no_full_pathname)))

insert image description here

2.2.4os.path.exists(path)

Determine whether path points to an existing path or an opened file descriptor, return True if it exists, and return False if it does not exist

full_pathname="/proc/bus/pci/3a/08.0" # 路径path存在
print("全路径名称对应的目录是否存在?{}".format(os.path.exists(full_pathname)))

insert image description here

no_full_pathname="/demo/none.cpp" # 路径path不存在
print("全路径名称对应的目录是否存在?{}".format(os.path.exists(no_full_pathname)))

insert image description here

2.2.5os.path.isabs(path)

Determine whether the path is an absolute path, return True if it is, return False if it is not or does not exist. On Unix it simply starts with a slash, while on Windows it can start with a slash (or backslash) minus the drive letter.

abs_pathname="/proc/bus/pci/3a/08.0" # 路径path存在
print("全路径名称对应的目录是否为绝对路径?{}".format(os.path.isabs(abs_pathname)))

insert image description here

rel_pathname="./nnunet/__init__.py" # 路径path是相对路径
print("全路径名称对应的目录是否绝对路径?{}".format(os.path.isabs(rel_pathname)))

insert image description here

no_pathname="./nnunet/none.py" # 路径path是不存在
print("全路径名称对应的目录是否绝对路径?{}".format(os.path.isabs(no_pathname)))

insert image description here

2.2.6os.path.isfile(path)

Return True if path is a symbolic link to an existing file or a path to an existing file. Returns False if path is a folder path or does not exist.

ls -li /opt/conda/bin/python* # 带inode节点信息并长格式查看python开头的文件和文件夹

insert image description here

From the above figure, it can be found that /opt/conda/bin/python is a symbolic link (soft link) pointing to an existing file path /opt/conda/bin/python3.7

abs_pathname="/opt/conda/bin/python3.7" # path为一个已存在文件路径
print("全路径名称对应的文件是否存在?{}".format(os.path.isfile(abs_pathname)))

insert image description here

symbolic_link="/opt/conda/bin/python" # path为指向一个已存在文件/opt/conda/bin/python3.7的符号链接
print("全路径名称对应的文件是否存在?{}".format(os.path.isfile(symbolic_link)))

insert image description here

abs_path="/opt/conda/bin/" # 文件夹路径
print("全路径名称对应的文件是否存在?{}".format(os.path.isfile(abs_path)))

insert image description here

no_full_pathname="/demo/none.cpp" # 路径path不存在
print("全路径名称对应的文件是否存在?{}".format(os.path.isfile(no_full_pathname)))

insert image description here

2.2.7os.path.isdir(path)

Returns True if path is a symbolic link to an existing folder or a path to an existing folder. Returns False if path is a file path or does not exist.

ls /code/nnunet/ # 查看已存在文件夹路径/code/nnunet/

insert image description here

ln -s /code/nnunet/ ./symlink2codennunet # 当前目录即root下创建一个软链接指向一个已存在文件夹路径/code/nnunet/
ls -l /root/

insert image description here

It can be seen from the figure above that there is a soft link symlink2codennunet in the home directory of the root user pointing to an existing folder path

exist_dir_path="/code/nnunet/"# path为一个已存在文件夹路径
print("全路径名称对应的文件夹是否存在?{}".format(os.path.isdir(exist_dir_path)))

insert image description here

exist_dir_symlink="/root/symlink2codennunet/"# path为指向一个已存在文件夹的符号链接
print("全路径名称对应的文件夹是否存在?{}".format(os.path.isdir(exist_dir_symlink)))

insert image description here

exist_file_path="/opt/conda/bin/python3.7"# path为一个已存在文件路径
print("全路径名称对应的文件夹是否存在?{}".format(os.path.isdir(exist_file_path)))

insert image description here

no_path="/demo/none.cpp" # 路径path不存在
print("全路径名称对应的文件夹是否存在?{}".format(os.path.isdir(no_path)))

insert image description here

2.2.8os.path.islink(path)

Returns True if path represents an existing symbolic link, otherwise returns False. Always returns False if the Python runtime does not support symbolic links

exist_symbolic_link="/opt/conda/bin/python" # path为指向一个已存在的符号链接
print("全路径名称对应的符号链接是否存在?{}".format(os.path.islink(exist_symbolic_link)))

insert image description here

no_symbolic_link="/demo/no_link" # path为指向一个不存在的符号链接
print("全路径名称对应的符号链接是否存在?{}".format(os.path.islink(no_symbolic_link)))

insert image description here

exist_file_path="/opt/conda/bin/python3.7"# path为一个已存在文件路径
print("全路径名称对应的符号链接是否存在?{}".format(os.path.islink(exist_file_path)))

insert image description here

exist_dir_path="/root/"# path为一个已存在文件夹路径
print("全路径名称对应的符号链接是否存在?{}".format(os.path.islink(exist_dir_path)))

insert image description here

2.2.9os.path.join(path, *paths)

Joins two or more path sections, interpolating as needed /. If a part of the parameter is an absolute path, the path before the absolute path will be discarded, and the connection will start from the absolute path part. If the last part is empty, the result will end with a delimiter.

previous_path,abs_dirname,basename,empty_part="model","/code","demo.py",""
print("参数中某个部分是绝对路径拼接后为{}".format(os.path.join(previous_path,abs_dirname,basename)))

insert image description here

print("拼接两个或多个路径部分,按需要插入'/'拼接后为{}".format(os.path.join(previous_path,basename)))

insert image description here

print("最后一部分为空以分隔符结尾{}".format(os.path.join(previous_path,basename,empty_part)))

insert image description here

2.2.10os.path.normcase(path)

Normalizes the case of path names. On Windows, convert all characters in path names to lowercase, and convert forward slashes to backslashes. On other operating systems, the path is returned unmodified.

Linux operating system

print("当前操作系统模块名为:{}".format(os.name))
windows_style_path=r"C:/Users\defaultuser0/APPData"
print("Windows路径规范化后为{}".format(os.path.normcase(windows_style_path)))

insert image description here

Windows operating system

insert image description here

2.2.11os.path.split(path)

Splits the path path into a pair, (head, tail), where tail is the last part of the path and head is everything but the last part. The tail part will not contain a slash, and if path ends with a slash, tail will be empty. If there are no slashes in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes in head are stripped unless it is the root directory (ie it contains only one or more slashes).

norm_path="/nnunet/configuration.py" # 一般路径
ends_with_slash_path="/code/nnunet/" # 以斜杠结尾的路径
no_slash_path="HIP_Logo.png" # 没有斜杠的路径
empty_path="" # 空路径
root_path="/" # 根目录
print("一般路径head={},tail={}".format(*os.path.split(norm_path)))
print("以斜杠结尾的路径head={},tail={}".format(*os.path.split(ends_with_slash_path)))
print("没有斜杠的路径head={},tail={}".format(*os.path.split(no_slash_path)))
print("空路径head={},tail={}".format(*os.path.split(empty_path)))
print("根目录head={},tail={}".format(*os.path.split(root_path)))

insert image description here

2.2.12os.path.splitext(path)

Split the path path into a pair, namely (root, ext), so that root + ext == path, where ext is empty or starts with an English period and contains at most one period. Periods before the path are ignored, eg splitext('.cshrc') returns ('.cshrc', '').

dir_path="/code/nnunet/" # 文件夹路径
multi_dot_file_path="/code/i.thy.py" # 包含多个句点的文件路径
single_dot_file_path="/code/we.py" # 包含单个句点的文件路径
starts_with_dot_file_path=".bashrc" # 以句点开头的路径
print("文件夹路径root={},ext={}".format(*os.path.splitext(dir_path)))
print("包含多个句点的文件路径root={},ext={}".format(*os.path.splitext(multi_dot_file_path)))
print("包含单个句点的文件路径root={},ext={}".format(*os.path.splitext(single_dot_file_path)))
print("以句点开头的路径root={},ext={}".format(*os.path.splitext(starts_with_dot_file_path)))

insert image description here

2.3 Other common commands

2.3.1os.name

The name of an imported module that depends on a specific operating system, returns 'posix' for Linux, 'nt' for Windows, and 'java' for the Java virtual machine

print("当前操作系统平台名称为{}".format(os.name))

insert image description here

2.3.2os.__file__

Returns the absolute path of the os module installation as a string

     import os
     print("os模块安装绝对路径是{}".format(os.__file__))

insert image description here

3. References

Guess you like

Origin blog.csdn.net/m0_46223009/article/details/128065092