os模块
查看操作系统类型
import os
os.name # 操作系统类型
如果是posix
,说明系统是Linux
、Unix
或Mac OS X
,如果是nt
,就是Windows
系统。
要获取详细的系统信息,可以调用uname()
函数
os.uname() # 操作系统的详细信息
值得注意的是uname()
函数在Windows
上不提供,也就是说,os
模块的某些函数是跟操作系统相关的。
环境变量
查看系统中定义的环境变量,都保存在os.environ
变量中
os.environ
获取某个环境变量的值,使用os.environ.get('key')
os.environ.get('JAVA_HOME')
操作文件和目录
操作文件和目录的函数一部分放在os
模块中,一部分放在os.path
模块中。以下是查看、创建、删除目录:
# 查看当前目录的绝对路径:
os.path.abspath('.')
# 在某个目录下创建一个新目录,首先把心目录的路径表示出来
os.path.join('/Users/cody', 'testdir')
# 创建一个目录
os.mkdir('/Users/cody/testdir')
# 删掉一个目录:
os.rmdir('/Users/cody/testdir')
将两个路径合成一个时,需要通过os.path.join()
函数。但是在mac/unix 和win平台是不同的
- mac(linux、unix): part-1/part-2
- win: part-1\part-2
同样拆分路径(这些拆分不需要路径真实存在,只对字符串操作)时,也需要通过os.path.split()
函数,拆分后的两部分,后一部分总是最后级别的目录或文件名:
os.path.split('/Users/codycc/testdir/file.txt')
('/Users/codycc/testdir', 'file.txt')
os.path.splitext()
可以直接得到文件的扩展名
os.path.splitext('/Users/codycc/testdir/file.txt')
('/Users/codycc/testdir/file', '.txt')
对文件重名和对文件删除
# 文件重名
os.rename('test.txt', 'test.py')
# 删除文件
os.remove('test.py')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-26-187f1befa2fb> in <module>()
1 # 文件重名
----> 2 os.rename('test.txt', 'test.py')
3 # 删除文件
4 os.remove('test.py')
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt' -> 'test.py'
列出当前目录下的所有目录
[x for x in os.listdir('.') if os.path.isdir(x)]
['.ipynb_checkpoints']