使用os
模块的基本功能
# import os # f= os.name #查看操作系统类型 # print(f)
如果是posix
,说明系统是Linux
、Unix
或Mac OS X
,如果是nt
,就是Windows
系统。
要获取详细的系统信息,可以调用uname()
函数
注意uname()
函数在Windows上不提供
在操作系统中定义的环境变量,全部保存在os.environ
这个变量中
要获取某个环境变量的值,可以调用os.environ.get('key')
操作文件和目录
# import os # a=os.path.abspath('.')#查看当前目录的绝对路径 # os.path.join('D:\桌面\py','whord')#在某个目录下创建一个新目录,首先把新目录的完整路径表示出来 # b=os.mkdir('D:\桌面\py\whord')#创建一个文件夹 # c=os.rmdir('D:\桌面\py\whord')#删除一个文件夹 # print(a) # print(b) # print(c)
把两个路径合成一个时,不要直接拼字符串,而要通过os.path.join()
函数,这样可以正确处理不同操作系统的路径分隔符。
文件重命名
# import os # f=os.rename('D:\桌面\py\hello.txt','D:\桌面\py\1.py') #文件重命名 # c=os.remove('D:\桌面\py\1.py') #删除文件 # print(f) # print(c)