Python文件属性模块Os.path介绍
os.path模块主要用于文件属性获取和判断,在编程中会经常用到,需要熟练掌握。以下是该模块的几种常用方法。
os.path官方文档:http://docs.python.org/library/os.path.html
Os.path模块的重要方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
os.path.abspath(path) #返回绝对路径 os.path.basename(path) #返回文件名 os.path.commonprefix(list) #返回list(多个路径)中,所有path共有的最长的路径。 os.path.dirname(path) #返回文件路径 os.path.exists(path) #路径存在则返回True,路径损坏返回False os.path.lexists #路径存在则返回True,路径损坏也返回True os.path.expanduser(path) #把path中包含的"~"和"~user"转换成用户目录 os.path.expandvars(path) #根据环境变量的值替换path中包含的”$name”和”${name}” os.path.getatime(path) #返回最后一次进入此path的时间。 os.path.getmtime(path) #返回在此path下最后一次修改的时间。 os.path.getctime(path) #返回path的大小 os.path.getsize(path) #返回文件大小,如果文件不存在就返回错误 os.path.isabs(path) #判断是否为绝对路径 os.path.isfile(path) #判断路径是否为文件 os.path.isdir(path) #判断路径是否为目录 os.path.islink(path) #判断路径是否为链接 os.path.ismount(path) #判断路径是否为挂载点() os.path.join(path1[, path2[, ...]]) #把目录和文件名合成一个路径 os.path.normcase(path) #转换path的大小写和斜杠 os.path.normpath(path) #规范path字符串形式 os.path.realpath(path) #返回path的真实路径 os.path.relpath(path[, start]) #从start开始计算相对路径 os.path.samefile(path1, path2) #判断目录或文件是否相同 os.path.sameopenfile(fp1, fp2) #判断fp1和fp2是否指向同一文件 os.path.samestat(stat1, stat2) #判断stat tuple stat1和stat2是否指向同一个文件 os.path.split(path) #把路径分割成dirname和basename,返回一个元组 os.path.splitdrive(path) #一般用在windows下,返回驱动器名和路径组成的元组 os.path.splitext(path) #分割路径,返回路径名和文件扩展名的元组 os.path.splitunc(path) #把路径分割为加载点与文件 os.path.walk(path, visit, arg) #遍历path,进入每个目录都调用visit函数,visit函数必须有 3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有 文件名,args则为walk的第三个参数 os.path.supports_unicode_filenames #设置是否支持unicode路径名 |
os.path模块的使用实例
将文件夹下所有图片名称加上’_py’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import re import os import time #str.split(string)分割字符串 #'连接符'.join(list) 将列表组成字符串 def change_name(path): global i if not os.path.isdir(path) and not os.path.isfile(path): return False if os.path.isfile(path): file_path = os.path.split(path) #分割出目录与文件 lists = file_path[1].split('.') #分割出文件与文件扩展名 file_ext = lists[-1] #取出后缀名(列表切片操作) img_ext = ['bmp','jpeg','gif','psd','png','jpg'] if file_ext in img_ext: os.rename(path,file_path[0]+'/'+lists[0]+'_py.'+file_ext) i+=1 #注意这里的i是一个陷阱 #或者 #img_ext = 'bmp|jpeg|gif|psd|png|jpg' #if file_ext in img_ext: # print('ok---'+file_ext) elif os.path.isdir(path): for x in os.listdir(path): change_name(os.path.join(path,x)) #os.path.join()在路径处理上很有用 img_dir = 'E:\\meizitu\\xx' img_dir = img_dir.replace('\\','/') start = time.time() i = 0 change_name(img_dir) c = time.time() - start print('程序运行耗时:%0.2f'%(c)) print('总共处理了 %s 张图片'%(i)) |
执行结果
1 2 3 |
C:\Users\Administrator>E:\python\learn\os.py 程序运行耗时:0.04 总共处理了 6 张图片 |
未经允许不得转载:Python在线学习 » Python文件属性模块Os.path