标签:
os模块(2)
- 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
标签:
原文地址:http://www.cnblogs.com/superdo/p/4719191.html