PythonOS模块详解(完善版本)
导包:import os
一:系统模块
1、print(os.name) # nt 表示Windows 系统;'posix’表示Linux系统
2、print (os.sep) #输出当前操作系统的路径分隔符;windos 展示 “\” 或 “\”;linux ”/“
3、print(os.linesep) #输出当前操作系统的换行符
4、print(os.pathsep) #输出分割文件路径的分隔符
5、print (os.getenv(‘环境变量名称’)) #读取环境变量
6、print(os.environ) #获取系统环境变量
二:目录操作-增删改查
1、print(os.listdir(‘D:\pycharm\study2’)) # 列出该路径下所有的文件夹
2、os.mkdir() #创建一个目录
3、os.rmkdir() #删除一个空目录
4、print(os.mkdir(‘a’)) #生成 单层目录
5、print(os.rmdir(‘a’)) #删除单层空目录 ,若不为空则不删
6、print(os.makedirs(‘a\d\c’)) #递归生成多层目录
7、print(os.removedirs(‘a\d\c’)) #递归删除空文件夹,若文件夹有内容则保留
8、print(os.chdir(r’D:\pycharm’)) #改变当前脚本目录,到指定目录
9、print(os.remove()) #只能删文件,不能删文件夹
10、print(os.rename(‘a.txt’, ‘b.txt’)) # 更改文件或目录名
11、print(os.stat(‘b.txt’)) #获取文件的详细信息
三:Path部分
1、print (os.getcwd()) # 获取当前的工作目录
2、print(os.curdir) #返回当前目录
3、print(os.pardir) #返回当前目录的父目录
4、print(os.system(‘dir’)) #运行shell命令,直接显示
5、print(os.path.abspath(‘b.txt’)) #获取绝对路径
6、print(os.path.split(r’D:\pycharm\study2\b.txt’)) #将path分割成目录和文件名
7、print(os.path.dirname(r’D:\pycharm\study2\b.txt’)) #返回path的目录,也就是os.path.split(path)的第一个元素
8、print(os.path.basename(r’D:\pycharm\study2\b.txt’)) #返回path最后的文件名,也就是os.path.split(path)的第二个元素。
9、os.path.join(pthh1,[path2,[…]]) #将多个路径组合后返回。第一个绝对路径之前的参数将被忽略
10、os.path.getatime(path) #返回path所指向的文件或目录最后的存取时间
11、os.path.getmtime(path) #返回path所指向的文件或目录最后的修改时间
12、os.path.realpath(file)获取当前文件的绝对路径,__file__指当前文件
#当前文件路径
fp = os.path.realpath(file)
print (fp)
#输出结果
D:\SoftWare\autoTest\AutoRunTest\Public\Common\ReadConfigIni.py
#其他文件路径
fp = os.path.realpath(“config.ini”)
print (fp)
#输出结果
D:\SoftWare\autoTest\AutoRunTest\Public\Common\config.ini
**os.path.realpath(“PATH”)**参数说明:
1. PATH指一个文件的全路径作为参数
2. 如果给出的是一个目录和文件名,则输出路径和文件名,输出为tuple
3. 如果给出的是一个目录名,则输出路径和空文件名,输出为tuple
实际上,该函数的分割并不智能,它仅仅是以"PATH"中的最后一个"/"作为分隔符,分隔后,将索引为0的视为目录(路径),将索引
为1的视为文件名
file_path = os.path.split(“D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py”)
print (file_path)
#输出结果
(‘D:/SoftWare/autoTest/AutoRunTest/Public/Common/’, ‘ReadConfigIni.py’)
file_path = os.path.split(“D:/SoftWare/autoTest/AutoRunTest/Public/Common/”)
print (file_path)
#输出结果
(‘D:/SoftWare/autoTest/AutoRunTest/Public/Common/’, ‘’)
file_path = os.path.split(“D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py”)[0]
print (file_path)
#输出结果
D:/SoftWare/autoTest/AutoRunTest/Public/Common/
file_path = os.path.split(“D:/SoftWare/autoTest/AutoRunTest/Public/Common/ReadConfigIni.py”)[1]
print (file_path)
#输出结果
ReadConfigIni.py
四:文件存在判断
1、print(os.path.exists(‘b.txt’)) #如果path存在则返回true,否则返回false
2、os.path.isabs(path) #如果path是绝对路径则返回true
3、os.path.isfile(path) #如果path是一个存在的文件返回true,否则返回false

物联沃分享整理
物联沃-IOTWORD物联网 » PythonOS模块详解

发表评论