1、os库的基本介绍

os库提供通用的、基本的操作系统交互功能

  • os库是Python标准库,包含几百个函数
  • 常用路径操作:os.path子库,处理文件路径及信息
  • 进程管理:启动系统中其他程序
  • 环境参数:获得系统软硬件信息等环境参数

2、路径操作

os.path子库以path为入口,用于操作和处理文件路径
import os.path 或import os.path as op

os.path.abspath(path)	#返回path在当前系统中的绝对路径
>>>os.path.abspath("file.txt")
运行结果为:'C:\\Users\\file.txt'

os.path.normpath(path)		#归一化path的表示形式,统一用\\分隔路径
>>>os.path.normpath("D://file.txt")
运行结果为:'D:\\file.txt'

os.path.relpath(path)		#返回当前程序与文件之间的相对路径(relatice path)
>>>os.path.relpath("C://Users//file.txt")
运行结果为:'..\\..\\.\\..\\..Users\\file.txt'

os.path.dirname(path)		#返回path中的目录名称
>>>os.path.dirname("D://file.txt")
运行结果为:‘D:’

os.path.basename(path)		#返回path中最后的文件名称
>>>os.path.basename("D://file.txt")
运行结果为:'file.txt'

os.path.join(path,*paths)		#组合path与paths,返回一个路径字符串
>>>os.path.join("D:/","python/file.txt")
运行结果为:'D:/python/file.txt'

os.path.exists(path)		#判断path对应文件或目录是否存在,返回True或False
>>>os.path.exists("D://python//file.txt")
运行结果为:False

os.path.isfile(path)		#判断path所对应是否为已存在的文件,返回True或False
>>>os.path.isfile("D://python//file.txt")
运行结果为:True

os.path.isdir(path)			#判断path所对应是否为已存在的目录,返回True或False
>>>os.path.isdir("D://python//file.txt")
运行结果为:False

os.path.getatime(path)		#返回path对应文件或目录上一次的访问时间
>>>os.path.getatime("D:/python/file.txt")
运行结果为:1518356633.7551725

os.path.getmtime(path)		#返回path对应文件或目录最近一次的修改时间
>>>os.path.getmtime("D:/python/file.txt")
输出结果为:1518356633.7551725

os.path.getctime(path)		#返回path对应文件或目录的创建时间
os.path.getctime("D:/python/file.txt")
运行结果为:'Sun Feb 11 20:51:20 2018'

os.path.getsize(path)		#返回path对应文件的大小,以字节为单位
>>>os.path.getsize("D:/python/file.txt")
运行结果为:100768

3、进程管理

os.system(command)

  • 执行程序或命令command
  • 在Windows系统中,返回值为cmd的调用返回信息
import os
os.system("C:\\Windows\\System32\\calc.exe")
#直接打开了电脑自带的计算器

4、os库之环境参数

获取或改变系统环境信息:
os.chdir(path)		#修改当前程序操作的路径
>>>os.chdir("D:")

os.getcwd()			#返回程序的当前目录
>>>os.getcwd()
运行结果为:'E:\\python_pychram'

获取操作系统环境信息:
os.getlogin()		#获得当前系统登录用户名称
>>>os.getlogin()
运行结果为:'lenovo'

os.cpu_count()		#获得当前系统CPU数量
<<<os.cpu_count()
运行结果为:4

os.urandom(n)		#获得n个字节长度的随机字符串,通常用于加解密运算
>>>os.urandom(10)
b'k\xb0C\xb8\x95\x87\xbe\xd4r\xcb'