python中操作文件的模块有几种?
python中操作文件的模块有几种?
本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。
Python对文件操作采用的统一步骤是:打开—操作—关闭。
一、python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法
1.得到当前工作目录,即当前Python脚本工作的目录路径:os.getcwd()
2.返回指定目录下的所有文件和目录名:os.listdir()
3.函数用来删除一个文件:os.remove()
4.删除多个目录:os.removedirs(r"c:\python")
5.检验给出的路径是否是一个文件:os.path.isfile()
6.检验给出的路径是否是一个目录:os.path.isdir()
7.判断是否是绝对路径:os.path.isabs()
8.检验给出的路径是否真地存:os.path.exists()
9.返回一个路径的目录名和文件名:os.path.split()
二、文件综合操作实例
将文件夹下所有图片名称加上'_fc'
#-*-coding:utf-8-*-
importre
importos
importtime
#str.split(string)分割字符串
#'连接符'.join(list)将列表组成字符串
defchange_name(path):
globali
ifnotos.path.isdir(path)andnotos.path.isfile(path):
returnFalse
ifos.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']
iffile_extinimg_ext:
os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext)
i+=1#注意这里的i是一个陷阱
#或者
#img_ext='bmp|jpeg|gif|psd|png|jpg'
#iffile_extinimg_ext:
#print('ok---'+file_ext)
elifos.path.isdir(path):
forxinos.listdir(path):
change_name(os.path.join(path,x))#os.path.join()在路径处理上很有用
img_dir='D:\\xx\\xx\\images'
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))
以上就是python中操作文件的模块,大家在看完文章后,可以就这两种模块中的方法分别进行尝试,然后挑选出自己更为喜欢的操作模式。更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python包的导入方式有几种
python包的导入方式有几种本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、from...import导入frompackageimportmodule1,mo详情>>
2023-11-08 23:58:44
python参数是什么
python参数是什么1、概念Python中函数的参数是不变的对象。Python函数具有灵活的参数形式,但默认参数必须指向不变的对象。如果默认参数是可变...详情>>
2023-11-08 19:48:30
python使用items()遍历键值对
python使用items()遍历键值对字典可以用来存储各种方式的信息,所以有很多方式可以通过字典的所有键值对、键或值。说明1、即使通过字典,键值对...详情>>
2023-11-08 19:23:48
python按行读取文件的方法比较
python按行读取文件的方法比较1、read方法默认会把文件的所有内容一次性读取到内存。如果文件太大,对内存的占用会非常严重2、readline方法,re...详情>>
2023-11-08 18:22:27