练习 os 模块,需要的时候可以查询官方文档获取需要的函数。
os.sep
- 操作系统特定的路径分隔符
# Linux 平台
[root@payu ~]# python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import os
>>>
>>> os.sep
'/'
>>>
# Windows 平台
C:\Users\payun>python
Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import os
>>>
>>> os.sep
'\\'
>>>
os.name
- 操作系统类型
# Linux
>>> os.name
'posix'
>>>
# Windows
>>> os.name
'nt'
>>>
os.getcwd()
- 当前目录,相当于 pwd
>>> os.getcwd()
'/root'
>>>
os.chdir(path)
- 进入指定目录,相当于 cd
>>> os.chdir('Downloads')
>>> os.getcwd()
'/root/Downloads'
# 目录不存在会报错
>>> os.chdir('../tmp')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '../tmp'
>>> os.chdir('../../tmp')
>>> os.getcwd()
'/tmp'
>>>
os.listdir(path)
- 返回指定目录下的文件,相当于 ls -a
>>> os.listdir(os.getcwd())
['hsperfdata_root', 'localsoftfix.sh', '.esd-0', '.ICE-unix', 'pulse-vAE1BleSKdz8']
>>>
os.path.exists(file)
- 文件或目录是否存在
>>> os.path.exists('tmp')
False
>>> os.path.exists('.esd-0')
True
>>>
os.system(command)
- 执行 shell 命令
>>> os.system('touch payun.tmp')
0
>>>
>>> os.system('ls -l|grep payun')
-rw-r--r-- 1 root root 0 Sep 25 23:07 payun.tmp
0
>>>
os.remove(path)
- 删除指定文件
>>> os.remove('payun.tmp')
>>> os.system('ls -l|grep payun')
256
>>>
os.getenv()
- 获取环境变量
>>> os.getenv('LANG')
'en_US.UTF-8'
>>>
os.putenv(key, value)
- 设置环境变量
os.linesep
- 换行符
# Linux 下的换行符
>>> os.linesep
'\n'
>>>
# Windows 下的换行符
>>> os.linesep
'\r\n'
>>>