Python中的OS模块提供了可以使用依赖操作系统相关功能的方法.OS模块提供的让你可以与底层的操作系统交互, Windows, Mac or Linux与平台无关.
官方文档:
https://docs.python.org/3/library/os.html
在python界面中也可以通过如下命令来进行查看详细介绍.
>>import os
>>help(os)
This exports:
- allfunctions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
- os.path isone of the modules posixpath, or ntpath
- os.name is'posix', 'nt', 'os2', 'ce' or 'riscos'
- os.curdir isa string representing the current directory ('.' or ':')
- os.pardir isa string representing the parent directory ('..' or '::')
- os.sep isthe (or a most common) pathname separator ('/' or ':' or '\\')
- os.extsep isthe extension separator ('.' or '/')
- os.altsep isthe alternate pathname separator (None or '/')
- os.pathsepis the component separator used in $PATH etc
- os.linesepis the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpathis the default search path for executables
- os.devnullis the file path of the null device ('/dev/null', etc.)
os以及其子模块包含的功能很多,下面就简单介绍和记录下我遇到的或者常用的函数.当然关于我没有记录的函数或者功能,依然可以通过例如
>>help(os.path)
>>help(os.path.isfile)
的方法快速查找到对应的解释.
1: 关于path子模块
os.path.abspath() 获取文件或目录的绝对路径
os.path.dirname() 获取文件或目录的路径
os.path.basename() 获取文件或者是文件名
os.path.join() 连接两个或以上的目录与文件名.需要是绝对路径
os.path.split() 分割文件名与目录
os.path.splitext() 分离文件名与扩展名
os.path.isdir( rPath) 判断给出的路径是否是一个目录
os.path.isabs() 判断是否是绝对路径
os.path.isfile() 判断是否是文件
os.path.exists(rLocalDir) 判断路径时候存在
os.path.getsize(filename)获取文件大小
实例:前提是我已经创建了文件/work/python-practice/test.py
#####os.path.basename
>>>os.path.basename( '/work/python-practice/test.py' )
'test.py'
>>>os.path.basename( '/work/python-practice/' )
''
>>>os.path.basename( '/work/python-practice' )
'python-practice'
######os.path.join实例
>>>os.path.join( '/work', 'python-practice/' )
'/work/python-practice/'
>>>os.path.join( '/work', 'python-practice', 'test.py' )
'/work/python-practice/test.py
########os.path.split os.path.splitext实例
>>>os.path.split( '/work/python-practice/test.py' )
('/work/python-practice','test.py')
>>>os.path.split( '/work/python-practice' )
('/work','python-practice')
>>>os.path.split( '/work/python-practice/' )
('/work/python-practice','')
>>>os.path.splitext( '/work/python-practice/test.py' )
('/work/python-practice/test','.py')
>>>os.path.splitext( 'test.py' )
('test', '.py')
########os.path.isdir os.path.isabs os.path.isfile
>>>os.path.isdir('/work/python-practice/test.py')
False
>>>os.path.isdir('/work/python-practice/')
True
>>>os.path.isabs('/work/python-practice')
True
>>>os.path.isabs('/work/python-practice/test.py')
True
>>>os.path.isabs('.')
False
>>>os.path.isfile('/work/python-practice/test.py')
True
>>>os.path.isfile('/work/python-practice/')
False
#########os.path.exists实例
>>>os.path.exists( './work' )
False
>>>os.path.exists( './test.py' )
True
>>>os.path.exists( '/work/python-practice' )
True
###########os.path.getsize
>>>os.path.getsize('./test.py')
191
>>>os.path.getsize('/work/python-practice')
4096
2: 关于文件/目录/属性
os.getcwd 获取当前工作路径
os.listdir 列出某个路径下面所有的目录和文件os.remove( )删除文件
os.removedirs( ) 删除多个目录
os.unlink( ) Remove a file, same as remove(path)
os.access(path,os.W_OK)
os.makedirs( path,mode ) 创建文件
os.makedirs( ) 创建多级目录
os.mkdir( ) 创建单个目录
os.mknod( ) 创建空文件
os.stat(file)获取文件属性
os.chmod(file)修改文件权限与时间戳
os.walk( ) 遍历目录
os.rename(old,new)重命名
os.chdir("path") 切换工作路径
实例:
>>>os.getcwd
'/work/python-practice'
>>>os.listdir('/work/python-practice')
['13exmp-1.py','raw-input.py', 'test.py'] //也支持相对路径的输入
>>>os.access('test.py', os.W_OK)
True
>>>os.access('test.py', os.X_OK)
False
#############################################
access(path, mode)-> True if granted, False otherwise
The mode argumentcan be F_OK to test existence, orthe inclusive-OR of R_OK, W_OK, and X_OK.
os.F_OK作为access()的mode参数,测试path是否存在.
os.R_OK 包含在access()的mode参数中, 测试path是否可读.
os.W_OK 包含在access()的mode参数中,测试path是否可写.
os.X_OK 包含在access()的mode常驻中, 测试path时候可执行.
makedirs(name,mode=511)
#####################################
>>>os.stat('test.py')
posix.stat_result(st_mode=33184,st_ino=24641559, st_dev=2056L, st_nlink=1, st_uid=1000,
st_gid=1000,st_size=191, st_atime=1517560593, st_mtime=1462513105,st_ctime=1462513105)
>>>for root, dirs, files in os.walk('/work/python-practice'):
... print root (注意print前面要缩进, 注意格式)
... print dirs
... print files
...
#(输出结果很长,我就不贴出来了)
##################
os.walk是遍历目录常用的模块,它返回一个包含3个元素的元祖:(dirpath,dirnames, filenames)。dirpath是
以string字符串形式返回该目录下所有的绝对路径;dirnames是以列表list形式返回每一个绝对路径下的文件夹名
字;filesnames是以列表list形式返回该路径下所有文件名字。
###########################
3: 关于环境变量
os.getenv()和os.putenv()函数分别用来读取和设置环境变量
os.environ获取用户环境
os.environ.get()
os.environ.copy()
os.name 当前操作系统名字
os.uname()获取详细的操作系统信息
os.pathsep返回系统变量中path变量的分隔符
os.linesep返回当前系统的换行符
实例 :
>>> for keyin os.environ.keys():
... print(key)
...
#输出所有变量的名字
>>os.environ
#返回所有环境变量的名字以及对应的值.
>>>os.name
'posix'
#指示你正在使用的平台:os.name 对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
>>>os.uname()
('Linux', 'ubuntu','3.16.0-59-generic', '#79~14.04.1-Ubuntu SMP Mon Jan 18 15:41:27 UTC2016', 'x86_64')
>>> os.pathsep ':' #在Windows中是";"Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
os.execvpe(file, args, env)
4: 关于进程
os.getgid()获得当前进程的真实group id
os.getuid() 获取当前进程的user id
os.exit()终止当前进程
os.system(CMD)运行shell命令
os.execvpe(file, args,env)
实例:
>>> os.getuid()
1000
>>> os.getgid()
1000
>>> os.system('ls -l test.py')
-rw-r----- 1 me me 191 May 6 2016 test.py
0
###########################
execvpe(file, args,env)
Execute theexecutable file (which is searched for along $PATH)
with argumentlist args and environment env , replacing the
currentprocess.
args may be alist or tuple of strings.
##############################
以上应该是比较全面的介绍了, 不过应该还有些疏漏或者我不熟悉的应用, 以后遇到的再补上.