python中操作文件的模块的方法总结


Posted in Python onFebruary 04, 2021

在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 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]+'_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 = 0
change_name(img_dir)
c = time.time() - start
print('程序运行耗时:%0.2f'%(c))
print('总共处理了 %s 张图片'%(i))

实例扩展:

#! python 3
# -*- coding:utf-8 -*-
# Autor: GrayMac
import shutil
import os

basefileclass = '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中操作文件的模块有几种内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python定时器使用示例分享
Feb 16 Python
在Python的Flask框架下收发电子邮件的教程
Apr 21 Python
python WindowsError的错误代码详解
Jul 23 Python
Python3 加密(hashlib和hmac)模块的实现
Nov 23 Python
matplotlib绘图实例演示标记路径
Jan 23 Python
Django中如何防范CSRF跨站点请求伪造攻击的实现
Apr 28 Python
python中class的定义及使用教程
Sep 18 Python
python安装gdal的两种方法
Oct 29 Python
pytorch forward两个参数实例
Jan 17 Python
python实现发送带附件的邮件代码分享
Sep 22 Python
Python中使用aiohttp模拟服务器出现错误问题及解决方法
Oct 31 Python
Python try except finally资源回收的实现
Jan 25 Python
Python3利用openpyxl读写Excel文件的方法实例
Feb 03 #Python
python之openpyxl模块的安装和基本用法(excel管理)
Feb 03 #Python
python中time.ctime()实例用法
Feb 03 #Python
python中Array和DataFrame相互转换的实例讲解
Feb 03 #Python
利用Python过滤相似文本的简单方法示例
Feb 03 #Python
python time.strptime格式化实例详解
Feb 03 #Python
Python字符串的15个基本操作(小结)
Feb 03 #Python
You might like
discuz论坛 用户登录 后台程序代码
2008/11/27 PHP
php中mail函数发送邮件失败的解决方法
2014/12/24 PHP
javascript 常用关键字列表集合
2007/12/04 Javascript
Prototype 学习 Prototype对象
2009/07/12 Javascript
使用jquery插件实现图片延迟加载技术详细说明
2011/03/12 Javascript
用js实现控件的隐藏及style.visibility的使用
2013/06/14 Javascript
jQuery 全选/反选以及单击行改变背景色实例
2013/07/02 Javascript
Javascript基础 函数“重载” 详细介绍
2013/10/25 Javascript
javascript 小数取整简单实现方式
2014/05/30 Javascript
判断字符串的长度(优化版)中文占两个字符
2014/10/30 Javascript
什么是 AngularJS?AngularJS简介
2014/12/06 Javascript
Vue.js使用v-show和v-if的注意事项
2016/12/13 Javascript
微信小程序 开发之顶部导航栏实例代码
2017/02/23 Javascript
详解AngularJS脏检查机制及$timeout的妙用
2017/06/19 Javascript
基于Vue单文件组件详解
2017/09/15 Javascript
OkHttp踩坑随笔为何 response.body().string() 只能调用一次
2018/01/08 Javascript
ES6下子组件调用父组件的方法(推荐)
2018/02/23 Javascript
JS Object.preventExtensions(),Object.seal()与Object.freeze()用法实例分析
2018/08/25 Javascript
Vue自定义全局Toast和Loading的实例详解
2019/04/18 Javascript
JavaScript实现星级评价效果
2019/05/17 Javascript
vue倒计时刷新页面不会从头开始的解决方法
2020/03/03 Javascript
vue开发简单上传图片功能
2020/06/30 Javascript
基于Vant UI框架实现时间段选择器
2020/12/24 Javascript
介绍Python中内置的itertools模块
2015/04/29 Python
Python中的anydbm模版和shelve模版使用指南
2015/07/09 Python
Python字符串格式化输出方法分析
2016/04/13 Python
Python内置函数OCT详解
2016/11/09 Python
python入门前的第一课 python怎样入门
2018/03/06 Python
Win7 64位下python3.6.5安装配置图文教程
2020/10/27 Python
python实现微信自动回复功能
2018/04/11 Python
python实现网页自动签到功能
2019/01/21 Python
Python字典的核心底层原理讲解
2019/01/24 Python
在cmd中查看python的安装路径方法
2019/07/03 Python
使用Puppeteer爬取微信文章的实现
2020/02/11 Python
数学考试作弊检讨书300字
2015/02/16 职场文书
大学四年个人总结
2015/03/03 职场文书