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培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python中yagmail库有何用法?
python中yagmail库有何用法?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。yagmail库一直被称作是最有良心的库,主要的原因还是因...详情>>
2023-11-14 05:52:35
python中操作文件的模块有几种?
python中操作文件的模块有几种?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。Python对文件操作采用的统一步骤是:打开—操作—关...详情>>
2023-11-14 03:37:12
python time.asctime()的字符串返回
pythontime.asctime()的字符串返回在我们学习了一些time函数后,对于它们各自的用法有一定的了解,就可以配合其他函数同时作用。就拿time.ascti...详情>>
2023-11-14 02:27:35
pandas中如何使用合并append函数?
pandas中如何使用合并append函数?介绍了这么多关于pandas拼接的方法,那你知道如果想要拼接拼接一个或者多个,还可以追加serise到原来的datafra...详情>>
2023-11-14 01:29:58热门推荐
如何自定义Python库创建和使用?
沸python中strip()和split()如何作用于字符串?
热如何使用python中的input()函数?
热python oracle数据库如何安装?
新python pexpect模块是什么?
如何使用python实现图片处理?
python中yagmail库有何用法?
python中Mako库怎么用?
python中series如何转为list?
python中如何编写函数并调用?
pandas拼接字符串的cat()方法如何使用?
python中操作文件的模块有几种?
datime包在python中计算时间差
python time.asctime()的字符串返回
技术干货






