python中操作文件的模块的方法总结
在python中操作文件算是一个基本操作,但是选对了模块会让我们的效率大大提升。本篇整理了两种模块的常用方法,分别是os模块和shutil模块。相信这两种模块大家在之间的学习中有所涉及,那么关于具体的文件操作部分,我们一起往下看看都有哪些方法和实例吧。
本教程操作环境:windows7系统、python3版、Dell G3电脑。
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 -*-import reimport osimport time#str.split(string)分割字符串#'连接符'.join(list) 将列表组成字符串def change_name(path):global iif not os.path.isdir(path) and not os.path.isfile(path):return Falseif 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]+'_fc.'+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 = 'D://xx//xx//images'img_dir = img_dir.replace('//','/')start = time.time()i = 0change_name(img_dir)c = time.time() - startprint('程序运行耗时:%0.2f'%(c))print('总共处理了 %s 张图片'%(i))
实例扩展:
#! python 3# -*- coding:utf-8 -*-# Autor: GrayMacimport shutilimport osbasefileclass = 'basefile'#sourcefile:源文件路径 fileclass:源文件夹 destinationfile:目标文件夹路径def copy_file(sourcefile,fileclass,destinationfile): #遍历目录和子目录 for filenames in os.listdir(sourcefile): #取得文件或文件名的绝对路径 filepath = os.path.join(sourcefile,filenames) #判断是否为文件夹 if os.path.isdir(filepath): if fileclass == basefileclass : copy_file(filepath,fileclass + '/' + filenames,destinationfile + '/' + filenames) else : copy_file(filepath,fileclass,destinationfile + '/' + filenames) #判断是否为文件 elif os.path.isfile(filepath): print('Copy %s'% filepath +' To ' + destinationfile) #如果无文件夹则重新创建 if not os.path.exists(destinationfile): os.makedirs(destinationfile) shutil.copy(filepath,destinationfile) copy_file(sourcefile,basefileclass,destinationfile)
到此这篇关于python中操作文件的模块的方法总结的文章就介绍到这了,更多相关python中操作文件的模块有几种内容请搜索 以前的文章或继续浏览下面的相关文章希望大家以后多多支持 !
最后更新于 2021-10-24 08:08:58 并被添加「」标签,已有 位童鞋阅读过。
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处
相关文章
- HTML5探秘:用requestAnimationFrame优化Web动画
- 收纳博士抽真空压缩袋收纳袋棉被子衣物收缩袋行李箱衣服收纳袋子
- 芦花老字号海盐不加抗结剂不加碘200g炖煮专用海盐8袋
- Python实现随机爬山算法
- 婴儿纯棉新生儿围嘴口水巾夏天纱布防水吐奶围兜饭兜宝宝夏季薄款