Python 的标准库中的 os 模块包含普遍的操作系统功能。
获取cpu个数,获取操作系统类型,示例
import os
cpuCount = os.cpu_count()
print(cpuCount)
name = os.name
print('操作系统的名字是:{}'.format(name))
result = os.path.exists('1.homework.py')
if result :
print('存在')
else :
print('不存在')
print(result)
利用os模块对路径进行操作判断路径是否存在,获取文件的绝对路径,截取公共部分的路径,获取文件所在的路径更改当前所在路径,示例:
result = os.path.exists('C:/Users/a/Desktop/os测试/python.txt')
print(result)
reult = os.getcwd()
print(result)
result = os.path.abspath('.')
print(result)
result = os.path.abspath('..')
print(result)
# 获取指定文件的绝对路径
result = os.path.abspath('1.作业.py')
print(result)
result = os.path.exists('D:/课程/第六天/1.作业.py')
print('路径的basename:{}'.format(result))
result = os.path.commonpath(['D:/课程/第六天/1.作业.py','D:/课程/第六天/2.作业.py'])
print('路径的公共部分为:{}'.format(result))
# 注意以斜杠分割将路径分成几部分
result = os.path.commonpath(['http://www.baidu.com','http://www.jd.com'])
print('网址的公共部分为{}'.format(result))
result = os.path.dirname('c:/User/Administrator/Desktop/os测试/python.txt')
print(result)
# 更改当前所在路径
os.chdir('..')
利用os模块对文件进行操作并与time模块配合使用查看文件创建更改访问日期,和文件大小,示例:
import time
# c 文档是change 实际是:create
result = os.path.getctime('D:/课程/第六天/1.作业.py')
print('文件创建的日期{}'.format(time.localtime(result)))
result = os.path.getatime('D:/课程/第六天/1.作业.py')
print('文件的访问日期是{}'.format(time.localtime(result)))
# m: modify 修改
result = os.path.getmtime('D:/课程/第六天/1.作业.py')
print('文件的修改日期:{}'.format(time.localtime(result)))
# size 尺寸大小
result = os.path.getsize('D:/课程/第六天/1.作业.py')
# 获取的大小为字节大小 B
print('文件的大小为:{}'.format(result / 1024))
result = os.path.isfile('D:/课程/第六天/1.作业.py')
print('{}'.format(result))