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 Tkinter简单布局实例教程
Sep 03 Python
Python使用scrapy采集数据时为每个请求随机分配user-agent的方法
Apr 08 Python
Python 自动化表单提交实例代码
Jun 08 Python
PyTorch线性回归和逻辑回归实战示例
May 22 Python
python traceback捕获并打印异常的方法
Aug 31 Python
Python3 安装PyQt5及exe打包图文教程
Jan 08 Python
python中import与from方法总结(推荐)
Mar 21 Python
Python简易版停车管理系统
Aug 12 Python
python DataFrame转dict字典过程详解
Dec 26 Python
Python collections模块的使用方法
Oct 09 Python
在python中实现导入一个需要传参的模块
May 12 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
Terran兵种对照表
2020/03/14 星际争霸
Linux下将excel数据导入到mssql数据库中的方法
2010/02/08 PHP
php checkbox 取值详细说明
2010/08/19 PHP
用PHP代替JS玩转DOM的思路及示例代码
2014/06/15 PHP
页面利用渐进式JPEG来提升用户体验度
2014/12/01 PHP
Smarty模板常见的简单应用分析
2016/11/15 PHP
Jquery进度条插件 Progress Bar小问题解决
2011/07/12 Javascript
JavaScript高级程序设计(第3版)学习笔记8 js函数(中)
2012/10/11 Javascript
javascript jscroll模拟html元素滚动条
2012/12/18 Javascript
JSON 必知必会 观后记
2016/10/27 Javascript
vue分类筛选filter方法简单实例
2017/03/30 Javascript
javascript checkbox/radio onchange不能兼容ie8处理办法
2017/06/13 Javascript
JS实现商品筛选功能
2020/08/19 Javascript
细说webpack源码之compile流程-rules参数处理技巧(2)
2017/12/26 Javascript
解决vue单页面应用中动态修改title问题
2019/06/09 Javascript
Layui Form 自定义验证的实例代码
2019/09/14 Javascript
用js编写留言板
2020/03/17 Javascript
Antd-vue Table组件添加Click事件,实现点击某行数据教程
2020/11/17 Javascript
python3中dict(字典)的使用方法示例
2017/03/22 Python
关于python pyqt5安装失败问题的解决方法
2017/08/08 Python
python版简单工厂模式
2017/10/16 Python
Pycharm以root权限运行脚本的方法
2019/01/19 Python
opencv-python 读取图像并转换颜色空间实例
2019/12/09 Python
用Python生成HTML表格的方法示例
2020/03/06 Python
python神经网络编程实现手写数字识别
2020/05/27 Python
django 实现后台从富文本提取纯文本
2020/07/02 Python
手把手教你从PyCharm安装到激活(最新激活码),亲测有效可激活至2089年
2020/11/25 Python
用CSS3实现无限循环的无缝滚动的实例代码
2017/07/04 HTML / CSS
美国最大婚纱连锁店运营商:David’s Bridal
2019/03/12 全球购物
DELPHI中如何调用API,可举例说明
2014/01/16 面试题
高中毕业生登记表自我鉴定范文
2014/03/18 职场文书
竞选大队干部演讲稿
2014/09/11 职场文书
三国演义读书笔记
2015/06/25 职场文书
分享CSS盒子模型隐藏的几种方式
2022/02/28 HTML / CSS
Python实现Hash算法
2022/03/18 Python
Windows11 Insider Preview Build 25206今日发布 更新内容汇总
2022/09/23 数码科技