os模块(2)
介绍
- os.path模块,主要处理路径操作,包含了各种处理文件和文件名的方法。
os.path
常量
os.path.sep路径分隔符 (Unix为/,Win为\)os.path.pathsep多个路径间的分隔符,多用于环境变量 (Unix为:, Win为;)os.path.extsep后缀名符号 一般为.
路径
os.path.split分割路径为目录名和文件名os.path.dirname目录名os.path.basename文件名os.path.splitext分割路径为文件和扩展名os.path.join路径组合
代码
import os filename = '/Users/superdo/test.txt' # 分割路径 _dir, _file = os.path.split(filename) print _dir # /Users/superdo print _file # test.txt # 目录名 print os.path.dirname(filename) # /Users/superdo # 文件名 print os.path.basename(filename) # test.txt # 扩展名 _filename, _ext = os.path.splitext(filename) print _filename # /Users/superdo/test print _ext # .txt # 路径组合 f = os.path.join('Users', 'superdo', 'test.txt') print f # Users/superdo/test.txt
判断路径属性
os.path.exists文件是否存在os.path.isdir是否是目录os.path.isfile是否是文件os.path.islink是否是连接文件os.path.ismount是否是挂载文件os.path.isabs是否是绝对路径
代码
import os filename = '/Users/superdo/test.txt' print os.path.exists(filename) # 判断存在 print os.path.isdir(filename) # 判断文件夹 print os.path.isfile(filename) # 判断文件 print os.path.islink(filename) # 判断连接文件 print os.path.ismount(filename) # 判断挂载文件 print os.path.isabs(filename) # 判断绝对路径
路径变换
os.path.relpath相对路径os.path.abspath绝对路径os.path.normpath标准化路径os.path.commonprefix获得共同路径
代码
import os filename = '/Users/superdo/ac/../path.txt' # 获得相对路径 print os.path.relpath(filename) # 获得相对于当前路径的路径 print os.path.relpath(filename, '/Users') # 获得相对于/Users的路径 # 绝对路径 print os.path.abspath(filename) # 标准化路径 print os.path.normpath(filename) # 获得多个路径中的共同路径 f1 = '/Users/superdo/zergling/file.txt' f2 = '/Users/superdo/ac/file.txt' f3 = '/Users/superdo/horse/file.txt' print os.path.commonprefix([f1, f2, f3]) # /Users/superdo/
文件属性
os.path.getatime访问时间 (从os.stat获得)os.path.getmtime修改时间(从os.stat获得)os.path.getctime创建时间(从os.stat获得)os.path.getsize文件大小(从os.stat获得)
代码
import os import filename = '/Users/superdo/test.txt' print os.path.getatime(filename) print os.path.getmtime(filename) print os.path.getctime(filename) print os.path.getsize(filename)
相同文件
os.path.samefile对比文件os.path.sameopenfile对比打开文件os.path.samestat对比文件stat
代码
import os f1 = '/Users/superdo/file.txt' f2 = '/Users/superdo/file.txt' print os.path.samefile(f1, f2) fp1 = open(f1) fp2 = open(f2) print os.path.sameopenfile(fp1.fileno(), fp2.fileno()) fs1 = os.stat(f1) fs2 = os.stat(f2) print os.path.samestat(fs1, fs2)

本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 )
转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4719191.html