os overview
- os: Operating System
os use
-
Import os module
-
View the os module usage documentation
- help(os)
- dir(os)
import os
# 查看os模块说明文档
help(os)
# 查看os模块的属性和方法
print(dir(os))
os operating system related
- os.name: Get the system name
- os.environ: Get system environment variable information
- os.getenv('PATH'): Get the environment variable information of the specified name
- os.system(): execute system instructions
import os
# os.name:获取系统名称 nt代表window,posix代表linux
print(os.name)
# os.environ:获取系统环境变量信息
print(os.environ)
# os.getenv('PATH'):获取指定名称的环境变量信息
print(os.getenv('PATH'))
# os.system():执行系统指令
os.system('pwd') # linux系统
print(os.system('dir')) # windows系统
os directory related
- os.getcwd(): Get the current directory
- os.chdir(): switch directories
- os.listdir(): List the contents of the current directory
- os.mkdir(): Create an empty directory
- os.makedirs(): Recursively create multi-level directories
- os.rmdir(): delete empty directories
- os.rename(): Rename directory
- os.remove(): delete files
"""目录相关"""
# 获取当前所在目录 get current directory
print(os.getcwd())
# 切换目录 change directory
os.chdir('..')
# 列出当前目录下的所有文件
print(os.listdir())
# 创建空目录
os.mkdir('new')
# 递归创建多级空目录
os.makedirs('a/b/c')
# 删除空目录
os.rmdir('new')
# 重命名目录
os.rename('a', 'a1')
# 删除文件
os.remove('demo.txt')
os path related
path method | illustrate |
---|---|
os.path.abspath(path) | Return absolute path |
os.path.basename(path) | Return file name |
os.path.dirname(path) | Return file path |
os.path.split(path) | split path |
os.path.join(path) | splicing path |
os.path.exists(path) | Determine whether the path exists |
os.path.isdir(path) | Determine whether it is a directory |
os.path.isfile(path) | Determine whether it is a file |
os.path.getsize(path) | Get file size |
os path usage example
# 返回绝对路径
print(os.path.abspath("./os_demo.py"))
# 返回文件名
print(os.path.basename("/Users/xiaofo/coding/pythonProject/course/os_demo.py"))
# 返回文件路径
print(os.path.dirname("/Users/xiaofo/coding/pythonProject/course/os_demo.py"))
# 分割路径
print(os.path.split("/Users/xiaofo/coding/pythonProject/course/os_demo.py"))
# 拼接路径
print(os.path.join("/Users/xiaofo/coding/pythonProject/course", "os_demo.py"))
# 判断路径是否存在
print(os.path.exists("/Users/xiaofo/coding/pythonProject/course/os_demo.py"))
print(os.path.exists("./os_demo.py"))
# 判断是否是目录
print(os.path.isdir("../demos"))
# 判断是否是文件
print(os.path.isfile("./hello.py"))
# 获取文件大小
print(os.path.getsize("/Users/xiaofo/coding/pythonProject/course/os_demo.py"))
Finally, I would like to thank everyone who reads my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can take it directly:
This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!