1. 组织文件笔记(第9章)(代码下载)

1.1 文件与文件路径
通过import shutil调用shutil模块操作目录,shutil模块能够在Python 程序中实现文件复制、移动、改名和删除;同时也介绍部分os操作文件的函数。常用函数如下:

函数 用途 备注
shutil.copy(source, destination) 复制文件
shutil.copytree(source, destination) 复制文件夹 如果文件夹不存在,则创建文件夹
shutil.move(source, destination) 移动文件 返回新位置的绝对路径的字符串,且会覆写文件
os.unlink(path) 删除path处的文件
os.rmdir(path) 删除path处的文件夹 该文件夹必须为空,其中没有任何文件和文件
shutil.rmtree(path) 删除path处的文件夹 包含的所有文件和文件夹都会被删除
os.walk(path) 遍历path下所有文件夹和文件 返回3个值:当前文件夹名称,当前文件夹子文件夹的字符串列表,当前文件夹文件的字符串列表
os.rename(path) path处文件重命名

1.2 用zipfile 模块压缩文件
通过import zipfile,利用zipfile模块中的函数,Python 程序可以创建和打开(或解压)ZIP 文件。常用函数如下:

函数 用途 备注
exampleZip=zipfile.ZipFile(‘example.zip’) 创建一个ZipFile对象 example.zip表示.zip 文件的文件名
exampleZip.namelist() 返回ZIP 文件中包含的所有文件和文件夹的字符串的列表
spamInfo = exampleZip.getinfo(‘example.txt’) 返回一个关于特定文件的ZipInfo 对象 example.txt为压缩文件中的某一文件
spamInfo.file_size 返回源文件大小 单位字节
spamInfo.compress_size 返回压缩后文件大小 单位字节
exampleZip.extractall(path)) 解压压缩文件到path目录 path不写,默认为当前目录
exampleZip.extract(‘spam.txt’, path) 提取某一压缩文件当path目录 path不写,默认为当前目录
newZip = zipfile.ZipFile(‘new.zip’, ‘w’) 以“写模式”打开ZipFile 对象
newZip.write(‘spam.txt’, compress_type=zipfile.ZIP_DEFLATED) 压缩文件 第一个参数是要添加的文件。第二个参数是“压缩类型”参数
newZip.close() 关闭ZipFile对象

2. 项目练习

2.1 将带有美国风格日期的文件改名为欧洲风格日期

# 导入模块
import shutil
import os
import re
# Renames filenames with American MM-DD-YYYY date format to European DD-MM-YYYY. # 含美国风格的日期
# Create a regex that matches files with the American date format.
datePattern = re.compile(
# 匹配文件名开始处、日期出现之前的任何文本
r"""^(.*?) # all text before the date
# 匹配月份
((0|1)?\d)- # one or two digits for the month
# 匹配日期
((0|1|2|3)?\d)- # one or two digits for the day
# 匹配年份
((19|20)\d\d) # four digits for the year
(.*?)$ # all text after the date
""", re.VERBOSE) # 查找路径
searchPath='d:/' for amerFilename in os.listdir(searchPath):
mo = datePattern.search(amerFilename)
# Skip files without a date.
if mo == None:
continue
# Get the different parts of the filename.
# 识别日期
beforePart = mo.group(1)
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8) # Form the European-style filename. 改为欧洲式命名
euroFilename = beforePart + dayPart + '-' + \
monthPart + '-' + yearPart + afterPart
# Get the full, absolute file paths.
# 返回绝对路径
absWorkingDir = os.path.abspath(searchPath)
# 原文件名
amerFilename = os.path.join(absWorkingDir, amerFilename)
# 改后文件名
euroFilename = os.path.join(absWorkingDir, euroFilename)
# Rename the files.
print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename))
shutil.move(amerFilename, euroFilename) # uncomment after testing
Renaming "d:\今天是06-28-2019.txt" to "d:\今天是28-06-2019.txt"...

2.2 将一个文件夹备份到一个ZIP 文件


import zipfile
import os # 弄清楚ZIP 文件的名称
def backupToZip(folder):
# Backup the entire contents of "folder" into a ZIP file.
# 获得文件夹绝对路径
folder = os.path.abspath(folder) # make sure folder is absolute
# Figure out the filename this code should use based on
# what files already exist.
number = 1
while True:
# 压缩文件名
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
# 如果压缩文件不存在
if not os.path.exists(zipFilename):
break
number = number + 1 # Create the ZIP file.
print('Creating %s...' % (zipFilename))
# 创建新ZIP 文件
backupZip = zipfile.ZipFile(zipFilename, 'w')
# TODO: Walk the entire folder tree and compress the files in each folder.
print('Done.') # 提取文件目录
# 一层一层获得目录
# Walk the entire folder tree and compress the files in each folder.
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername)) # 压缩文件夹
# Add the current folder to the ZIP file.
backupZip.write(foldername) # Add all the files in this folder to the ZIP file.
for filename in filenames:
newBase = os.path.basename(folder) + '_'
# 判断文件是否是压缩文件
if filename.startswith(newBase) and filename.endswith('.zip'):
continue # don't backup the backup ZIP files
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.') backupToZip('image')
Creating image_1.zip...
Done.
Done.

2.3 选择性拷贝

编写一个程序,遍历一个目录树,查找特定扩展名的文件(诸如.pdf 或.jpg)。不论这些文件的位置在哪里,将它们拷贝到一个新的文件夹中。

import shutil
import os def searchFile(path, savepath):
# 判断要保存的文件夹路径是否存在
if not os.path.exists(savepath):
# 创建要保存的文件夹
os.makedirs(savepath)
# 遍历文件夹
for foldername, subfolders, filenames in os.walk(path):
for filename in filenames:
# 判断是不是txt或者pdf文件
if filename.endswith('txt') or filename.endswith('pdf'):
inputFile = os.path.join(foldername, filename)
# 保存文件路径
outputFile = os.path.join(savepath, filename)
# 文件保存
shutil.copy(inputFile, outputFile) searchFile("mytest", "save")

2.4 删除不需要的文件

编写一个程序,遍历一个目录树,查找特别大的文件或文件夹。将这些文件的绝对路径打印到屏幕上。


import os def deletefile(path):
for foldername, subfolders, filenames in os.walk(path):
for filename in filenames:
# 绝对路径
filepath = os.path.join(foldername, filename)
# 如果文件大于100MB
if os.path.getsize(filepath)/1024/1024 > 100:
# 获得绝对路径
filepath = os.path.abspath(filepath)
print(filepath)
# 删除文件
os.unlink(filepath) deletefile("mytest")

2.5 消除缺失的编号

编写一个程序,在一个文件夹中,找到所有带指定前缀的文件,诸如spam001.txt,spam002.txt 等,并定位缺失的编号(例如存在spam001.txt 和spam003.txt,但不存在spam002.txt)。让该程序对所有后面的文件改名,消除缺失的编号。


import os
import re
# 路径地址
path = '.'
fileList = []
numList = []
# 寻找文件
pattern = re.compile('spam(\d{3}).txt')
for file in os.listdir(path):
mo = pattern.search(file)
if mo != None:
fileList.append(file)
numList.append(mo.group(1)) # 对存储的文件排序
fileList.sort()
numList.sort() # 开始缺失的文件编号
# 编号从1开始
index = 1
# 打印不连续的文件
for i in range(len(numList)):
# 如果文件编号不连续
if int(numList[i]) != i+index:
inputFile = os.path.join(path, fileList[i])
print("the missing number file is {}:".format(inputFile))
outputFile = os.path.join(path, 'spam'+'%03d' % (i+1)+'.txt')
os.rename(inputFile, outputFile)
the missing number file is .\spam005.txt:

最新文章

  1. calender 软文
  2. 关于git SSH Key的 生成
  3. javaWeb加载Properties文件
  4. Liferay7 BPM门户开发之33: Portlet之间通信的3种方式(session、IPC Render Parameter、IPC Event、Cookies)
  5. unsigned long类型转换为CString出现的问题
  6. IOS 本地通知UILocalNotification
  7. C#调用VC dll输出参数
  8. 玩转Web之servlet(四)---B/S是如何使用http协议完成通信过程的
  9. svn 中commit时必须填写备注信息如何设置
  10. Java面向对象 IO (一)
  11. oracle的start with connect by prior如何使用
  12. [js]promise学习2
  13. Windows Service 项目中 Entity Framework 无法加载的问题
  14. 一步步配置cordova android开发环境
  15. VS2017 Pro未能找到路径“……\bin\roslyn\csc.exe”的解决方案
  16. Django 数据库操作进阶F和Q操作
  17. Centos更新配置文件命令
  18. 网页抓取信息(php正則表達式、php操作excel)
  19. 配置zabbix_server通过zabbix_proxy进行监控Host
  20. scjp考试准备 - 10 - 类型转换

热门文章

  1. Es 学习笔记 (1)
  2. 微服务架构学习与思考(10):微服务网关和开源 API 网关01-以 Nginx 为基础的 API 网关详细介绍
  3. JUI(6)线程池
  4. 使用python获取window注册表值的方法
  5. python创建icon图标
  6. numpy常用知识点备忘
  7. gin框架——使用viper读取配置
  8. 京东云开发者|软件架构可视化及C4模型:架构设计不仅仅是UML
  9. CodeTON Round 3 (C.差分维护,D.容斥原理)
  10. Django系列---开发一