Python os 标准库使用

os模块是python自带的一个核心模块,用于和操作系统对象进行交互。

1.导入模块获取帮助

>>> import os
>>> help(os)
>>> dir(os)

2.常用方法

2.1 os.sep 获取当前系统的路径分隔符

>>> print os.sep

/

2.2 os.linesep 获取当前平台使用的行终止符

>>> os.linesep

' '

2.3 os.name 判断正在使用的平台
       Windows 返回 ‘nt'; Linux 返回’posix'

>>> print os.name
posix

2.4 os.getcwd() 获取当前目录

>>> print os.getcwd()
/home/oracle

2.5 os.listdir 列出给定目录里的文件

>>> print os.listdir(os.getcwd())
['.gconfd', '.Trash', '1_dy.sql']

2.6 os.remove() 删除指定的文件

>>> os.remove('/u02/rman_dest2/20151023095720.zip')

2.7 os.rename() 重命名对象名

>>> os.rename('/u02/rman_dest2/20151023/113950.zip','/u02/rman_dest2/20151023/aaa.zip')

2.8 os.rmdir() 删除指定目录
         删除不掉非空目录,删除非空目录可以 os.system('rm -rf path') 或 import shutil  shutil.rmtree(path)

>>> os.rmdir('/u02/rman_dest2/20151023')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OSError: [Errno 39] Directory not empty: '/u02/rman_dest2/20151023'

2.9 os.mkdir() 创建指定目录

>>> os.mkdir('/u02/rman_dest2/20151024')

2.10 os.chdir() 改变当前目录

>>> os.chdir('/u02/rman_dest2/20151024')
>>> os.getcwd()
'/u02/rman_dest2/20151024'

2.11 os.system() 执行系统命令

>>> os.system('rm -rf /u02/rman_dest2/20151023')
0

2.12 os.path.exists()  检查指定对象是否存在  True/False

>>> os.path.exists('/u02/rman_dest2/20151023')
False
>>> os.path.exists('/u02/rman_dest2')
True

2.13 os.path.split() 切割给定对象,用来分割路径和文件名

>>> os.path.split('/u02/rman_dest2/aa')
('/u02/rman_dest2', 'aa')
>>> os.path.split('/u02/rman_dest2')   #总是切割出最后的
('/u02', 'rman_dest2')
>>> os.path.split('/u02/rman_dest2/')
('/u02/rman_dest2', '')

2.14 os.path.splitext()  分割文件名和扩张名

>>> os.path.splitext('113950.zip')
('113950', '.zip')

2.15 os.path.bashname() 获得给定对象的文件名

>>> os.path.basename('/u02/rman_dest2/aa')
'aa'
>>> os.path.basename('/u02/rman_dest2')   #总是获得最后一个
'rman_dest2'
>>> os.path.basename('/u02/rman_dest2/')
''

2.16 os.path.dirname() 获得给定对象的路径

>>> os.path.dirname('/u02/rman_dest2/aa')
'/u02/rman_dest2'
>>> os.path.dirname('/u02/rman_dest2')
'/u02'
>>> os.path.dirname('/u02/rman_dest2/')
'/u02/rman_dest2'

2.17 os.path.abspath()  获得给定对象的决定路径

>>> os.path.abspath('.')
'/u02/rman_dest2/20151024'
>>> os.path.abspath('../')
'/u02/rman_dest2'
>>> os.path.abspath('..')
'/u02/rman_dest2'

2.18 os.path.getsize() 获得给定对象文件的大小

>>> os.path.getsize('/u02/rman_dest2/20151023/113950.zip')
286082025L

2.19 os.path.join(path,name) 连接目录和文件名

>>> os.path.join('/u02/','113950.zip')
'/u02/113950.zip'
>>> os.path.join('/u02','113950.zip')
'/u02/113950.zip'

2.20 os.path.isfile()  判断对象是否为文件 True/False

>>> os.path.isfile('/u02/rman_dest2/20151023/113950.zip')
True
>>> os.path.isfile('/u02/113950.zip')   #该文件就不存在
False
>>> os.path.isfile('/u02')
False

2.21 os.path.isdir()  判断对象是否为目录 True/False

>>> os.path.isdir('/u02/rman_dest2/20151023/113950.zip')
False
>>> os.path.isdir('/u02/113950.zip')
False
>>> os.path.isdir('/u02')
True

--待续

原文地址:https://www.cnblogs.com/myrunning/p/4904197.html