os 模块提供了很多允许你的程序与操作系统直接交互的功能。
不带path的方法 |
os.getcwd() # 得到当前工作目录,即当前Python解释器的目录路径
# vi /Users/huangqiushi/PycharmProjects/checkServer/test_os.py import os print(os.getcwd()) # cd / # python /Users/huangqiushi/PycharmProjects/checkServer/test_os.py 输出:/ # cd /tmp # python /Users/huangqiushi/PycharmProjects/checkServer/test_os.py 输出/tmp
os.listdir() # 返回指定目录下所有文件和目录名
>>> import os >>> os.listdir(‘.‘) [‘.DS_Store‘, ‘atm_shopmall‘, ‘atm_shopmall.zip‘, ‘startMyPython3.0‘] >>> os.listdir() # 默认目录就是当前目录 [‘.DS_Store‘, ‘atm_shopmall‘, ‘atm_shopmall.zip‘, ‘startMyPython3.0‘]
os.remove() # 删除一个文件的方法
>>> os.remove(‘atm_shopmall.zip‘) >>> os.listdir() [‘.DS_Store‘, ‘atm_shopmall‘, ‘startMyPython3.0‘]
os.linesep # 返回当前平台使用的行终止符
>>> os.linesep ‘\n‘ # Linux/OS X都是使用‘\n‘ windows使用‘\r\n‘
os.name # 提示正在使用的平台
>>> os.name ‘posix‘ # 对于Linux/Unix用户,都是"posix" windows是"nt"
os.rename() # 对一个文件改名
>>> os.listdir(os.getcwd()) [‘.idea‘, ‘checkCpu.py‘, ‘checkServer.py‘, ‘test_os.py‘] >>> os.rename(‘test_os.py‘,‘test_new.py‘) >>> os.listdir(os.getcwd()) [‘.idea‘, ‘checkCpu.py‘, ‘checkServer.py‘, ‘test_new.py‘]
os.getenv("HOME") # 读取操作系统环境变量HOME的值