os模块为我们提供了与操作系统交互的便捷接口。它功能强大,我们日常工作中可能只使用了其部分功能。今天,我们将探讨一些不常用但非常实用的功能。
实用功能介绍
获取当前代码执行路径
>>> import os >>> os.getcwd() 'C:\\Users\\Administrator'
获取 PATH 环境变量值
>>> os.getenv('PATH')
'D:\\Python37\\Scripts\\;D:\\Python37\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\ATI Technologies\\ATI.ACE\\Core-Static;C:\\Program Files (x86)\\AMD\\ATI.ACE\\Core-Static;D:\\Soft\\Microsoft VS Code\\bin;D:\\Python37\\Lib\\site-packages;D:\\Soft\\Git\\cmd;D:\\Soft\\Nodejs;D:\\Soft\\Nodejs\\node_global;C:\\Users\\Administrator\\AppData\\Roaming\\npm;D:\\Python37\\lib\\site-packages\\pywin32_system32'获取文件在操作系统中的表示格式
>>> os.fspath('C:\\Users\\Administrator\\Desktop\\1.png')
'C:\\Users\\Administrator\\Desktop\x01.png'获取当前控制台的尺寸
>>> os.get_terminal_size() os.terminal_size(columns=80, lines=30) # 将控制台拉大一点 >>> os.get_terminal_size() os.terminal_size(columns=80, lines=31)
创建文件夹&查看文件列表
>>> os.mkdir('testOS')
>>> os.listdir()
['testOS', 'Videos', 'VirtualBox VMs', '「开始」菜单']移除文件
[PHP房产程序|BBWPS]功能介绍 1、5种信息类别发布:出租、求租、出售、求购、楼盘信息,支持会员发布信息审核; 2、灵活的信息参数设置; 3、充足的信息字段; 4、简单易用的发布/编辑功能,支持配图上传; 5、灵活的信息管理功能; 6、信息输出伪静态,方便搜索引擎抓取数据; 7、支持RSS输出; 8、内置数据高速缓冲技术,可灵活设置缓冲功能是否启动及过期时间; 9、支持 Google 地图
os.rmdir('testOS')
>>> os.listdir()
['Videos', 'VirtualBox VMs', '「开始」菜单']判断是否为文件/夹
>>> os.path.isfile('testOS')
False
>>> os.path.isdir('testOS')
True执行命令

查看系统全部时间
>>> os.times() nt.times_result(user=0.1092007, system=0.2028013, children_user=0.0, children_system=0.0, elapsed=0.0)
查看当前登录的用户
>>> os.getlogin() 'Administrator'
关于更多用法,请移步至
docs.python.org。请注意,
Linux和
Windows在
os模块的使用上存在部分差异,
os对
Linux的支持更为全面。









