关注微信公众号(瓠悠笑软件部落),一起学习,一起摸鱼

python shutil module

shutil module 是 shell utilities 的简写,在Python 程序里面能够让你 copy, move, rename, 和 delete 文件。要使用 shutil 功能,你需要先导入 shutil 模块: import shutil

Copying Files and Folders

shutil 模块提供了拷贝文件乃至整个文件夹的功能。shutil.copy(source, destination) 将会把 source 路径下的文件拷贝到 destination 路径下。(source 和 destination 都是字符串.) 如果 destination 是一个文件名, 它将会成为被拷贝文件的新名称。这个函数返回被拷贝文件的路径字符串。

  • shutil.copy(source, destination) 只会拷贝单个文件。
#! /usr/bin/python3
import shutil, osfor i in range(1,31):shutil.copy('./capitalsquiz' + str(i) + '.txt', './txt')shutil.copy('./capitalsquiz_answers' + str(i) +'.txt', './txt')
  • shutil.copytree(source, destination) 将会拷贝整个文件夹 和 这个文件夹下面的所有文件。
    使用 shutil.copytree 方法时,destination 将是一个新创建的文件夹名称。如果这个文件夹已经在磁盘中存在,将回报错。
#! /usr/bin/python3
import shutil, os
shutil.copytree('./txt','./txt2')

Moving and Renaming Files and Folders

调用 shutil.move(source, destination) 将会把 source 路径下的文件或者文件夹移动到 destination 路径下,然后返回一个字符串,表示新位置的绝对路径。如果 destination 指向的是一个文件夹。那么 source file 将移到 destination 文件夹,并且保持它当前的名字。如果 destination 文件夹下面已经有同样名称的文件,会被直接覆盖掉。 destination 也可以用于指定为一个文件名。

Finally, the folders that make up the destination must already exist, or else Python will throw an exception.

永久性的删除文件和文件夹

你可以使用 os module 里面的函数删除一个文件或者一个空的文件夹。
而删除文件夹及其所有内容, 就要使用 shutil module.

  • 调用 os.unlink(path) 监会删除path指定的文件
  • 调用 os.rmdir(path) 将会删除 path 指定的文件夹,这个文件夹必须是空的。
  • 调用 shutil.rmtree(path)将会移除path指定的文件夹,它所包含的所有文件或子文件夹,也会一并删除。

使用send2trash module 安全删除

由于Python 内置的模块 shutil.rmtree() 函数将不可逆第删除文件和文件夹。使用的时候要谨慎。更稳妥的方法是使用第三方 send2trash module. 他将把文件移到垃圾回收箱。但是不支持从垃圾回收箱恢复文件,你只能手动恢复。

Walking a Directory Tree

如果你想重命名所有文件夹和它所包含的子文件夹里面的文件的文件名。你可以使用 os.walk() 函数。

#! /usr/bin/python3
import osfor folderName, subfolders, filenames in os.walk('/home/test2'):print('The current folder is ' + folderName)for subfolder in subfolders:print('Subfolder of' + folderName + ': ' + subfolder)for filename in filenames:print('FILE INSIDE ' + folderName + ': ' + filename)print('')

os.walk() 函数将产地一个字符串值:一个文件夹的路径。 os.walk() 函数将会遍历这个文件加的所有文件或子文件夹。在每次循环迭代中,他将返回三个值:

  • a string of the current folder’s name 当前文件夹的名称
  • a list of strings of the folders in the current folder 当前文件夹下的所有folders名称
  • a list of strings of the files in the current folder
    By current folder, I mean the folder for the current iteration of the for loop. The current working directory of the program is not changed by os.wark().

使用 zipfile module 压缩文件

你可能熟悉 ZIP 文件(以 .zip 作为文件后缀), 它能包含许多压缩后的文件。压缩一个文件能够减少他的大小。如果要在网络中传输这个文件,将会很有用。由于 ZIP 文件能够包含多个文件和子文件夹。因此把多个文件压缩打包进一个文件是很方便的。这个打包后的文件,称之为归档文件: archive file.

读取 ZIP Files

#! /usr/bin/python3
import zipfile, os
sourceZip = zipfile.ZipFile('source.zip')
print(sourceZip.namelist())
fileInfo = sourceZip.getinfo('star.py')
print(fileInfo.file_size)
print(fileInfo.compress_size)
print('Compressed file is %sx smaller!' % (round(fileInfo.file_size / fileInfo.compress_size, 2)))
sourceZip.close()

一个 ZipFile 对象有一个 namelist() 方法,他会返回一个 包含 string 的 List. 代表着这个 ZIP 文件所包含的所有文件 和 文件夹的名称。这些名称可以作为参数传递给ZipFile 的 getinfo() 方法,以获取一个 ZipInfo object. 这个对象包含自己的属性:

  • file_size 原始文件的大小,单位是bytes
  • comress_size 被压缩后文件的大小,单位是bytes
    当 ZipFile 是有一个文件压缩而成时, ZipInfo 对象包含一些关于这个文件的有用信息。

Extracting from ZIP Files

  • extractall()
    ZipFile object 的extractall() 方法将会把 ZIP 文件的包含的所有文件和文件夹都提取出来,放到当前所在目录。也可以传一个目录路径。用于保存提取出的文件。
#! /usr/bin/python3
import zipfile, os
sourceZip = zipfile.ZipFile('source.zip')
sourceZip.extractall('./extract_source')
sourceZip.close()
  • extract()
  • ZipFile object 的 extract(filename) 方法将会从 ZIP 文件中提取出一个文件,filename必须是namelist()方法返回的列表中的一个值。你也可以指定第二个参数,用于指明被提取文件要保存的路径。如果这个路径所指出的文件夹不存在,系统将会创建它。extract()方法将会返回被提取文件的绝对路径。

Creating and Adding to ZIP Files

如果想创建你自己的压缩归档文件(ZIP files),你必须以写模式打开 ZipFile object. 以’w’作为第二个参数传递给 zipfile.ZipFile()方法,例如: zipfile.ZipFile(‘new.zip’, ‘w’) (这个和打开文件类似,‘w’ 作为第二个参数传递给 open() 方法)
当你传递一个 path 给 ZipFile object 的 write() 方法时,Python 将会压缩这个path所关联的文件,并添加到这个 ZIP file 中。write() 方法的第一个参数是你要添加的文件名。第二个参数是使用的压缩类型(compression type). 这个参数将告诉计算机采用什么算法来压缩这个文件。你可以一直传 zipfile.ZIP_DEFLATED. 它表示使用 deflate 压缩算法,这种算法对所有数据都有效。

#! /usr/bin/python3
import zipfile
newZip = zipfile.ZipFile('new.zip', 'w')
newZip.write('star.py', compress_type=zipfile.ZIP_DEFLATED)
newZip.close()

注意,如果目录里面已经有一个叫做new.zip的归档文件,运行程序时,newZip = zipfile.ZipFile(‘new.zip’, ‘w’) 会直接将这个文件清空。这个和打开文件是一样的。如果不想情况已有的归档文件,需要以追加模式打开。第二个参数传 ‘a’, 例如: zipfile.ZipFile(‘new.zip’, ‘a’)

Renaming Files with American-Style Dates to European-Style Dates

#! /usr/bin/python3
# renameDates.py - Renames filenames with American MM-DD-YYYY date format to European DD-MM-YYYY.
import shutil, os, re# Create a regex that matches files with the Americaon 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)# Loop over the files in the working directory.
for amerFilename in os.listdir('.'):mo = datePattern.search(amerFilename)# SKip files without a date.if mo == None:continue# Get the different parts of the filenamebeforePart = 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('.')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)

Project: Backing Up a Folder into a ZIP File

备份文件夹和文件夹里面的所有文件

#! /usr/bin/python3
# backupToZip.py - Copies an entire folder and its contents into
# a ZIP file whose filename increments.import zipfile, osdef 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 = 1while True:zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'if not os.path.exists(zipFilename):breaknumber = number + 1# Create the ZIP file.print('Creating %s...' % (zipFilename))backupZip = zipfile.ZipFile(zipFilename, 'w')# 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) + '_' # changedif filename.startwith(newBase) and filename.endswith('.zip'):continue # don't backup the backup ZIP filesbackupZip.write(os.path.join(foldername, filename))backupZip.close()print('Done.')backupToZip('\home\my-repo\pythonLearn')

python shutil module相关推荐

  1. Python Shutil模块

    When you need to work with high-level file operations like copying contents of a file, create a new ...

  2. ubuntu下,py2,py3共存,/usr/bin/python: No module named virtualenvwrapper错误解决方法

    2019独角兽企业重金招聘Python工程师标准>>> ubuntu下,py2,py3共存 运行virtualenvwrapper会报错如下: /usr/bin/python: No ...

  3. python 模块(Module)和包

    阿里云大学人工智能学前小测验-Python测验 19.以下关于模块说法正确的是 A. 一个.py就是一个模块 B. 任何一个普通的xx.py文件可以作为模块导入 C. 模块文件的扩展名一定是 .py ...

  4. python shutil模块用法实例分析_Python shutil模块用法实例分析

    分享大神指教Python中的shutil模块的rmtree()方法如分享大神指教Python中的shutil模块的rmtree()方法如何实现.思路是怎样的rmtree() 是用来删除文件目录及其中的 ...

  5. PyMOTW-3 (Python 3 Module of the Week) 翻译团队召集

    自翻译起始已经一个月过去了,目前翻译进度三分之一,PyMOTW 篇幅很大,翻译 PyMOTW 是一个偏大的工程,大概 140 篇文章,并且每篇文章里内容详实,例如这篇正则表达式的文章: https:/ ...

  6. VScode Python no module的解决方法

    VScode Python no module的解决方法 参考文章: (1)VScode Python no module的解决方法 (2)https://www.cnblogs.com/andy-0 ...

  7. python no module named pip_解决python No module named pip的问题

    解决python "No module named pip"的问题 python 升级后导致不能使用原来的pip命令 windows平台 cmd中敲命令:python -m ens ...

  8. Python shutil 模块详解

    Python shutil 模块详解 1.模块介绍 2.copytree 示例 3.move 示例 1.模块介绍 import shutil# copy data from file-like obj ...

  9. /usr/bin/python: No module named pip

    在安装 pip 工具时报错如下: /usr/bin/python: No module named pip 查找资料说先安装 ensurepip 模块,就可以恢复 pip: python -m ens ...

最新文章

  1. 腾讯千帆战略升级,推出企业应用连接器
  2. 扎克伯格凌晨放大招,说几句话能造世界的那种
  3. python的特点和优点-【Python面试】 Python 的特点和优点是什么?
  4. 图像处理:像素间的基本关系
  5. Port Forwarding Port Triggering
  6. 雅马哈发电机换机油教程_奥迪老A4B7 EA113 1.8T发动机严重烧机油大修彻底解决
  7. 论“前置测试模型”-1 概念篇
  8. Request load inbound error - COM_ATTRFRG_GEN 066
  9. Vue-- $attrs与$listeners的详解
  10. php7 mysql json 小程序_微信小程序JSON数组递交PHP服务端解析处理
  11. 第十一章:WebSocket
  12. 瞎扯系列:判断NPN及PNP管型之右手定则
  13. 【UVA10976】Fractions Again?!(结构体内重载运算符---水题)
  14. 基于SSM的社区宠物信息管理系统
  15. Hutool使用总结(VIP典藏版)
  16. 2.应用统计与随机过程第二章部分课上例题(平稳随机、各态历经)
  17. c#调用microsoft word将word另存为pdf
  18. ThreadLocal 源码之 expungeStaleEntry
  19. 【8.8gzoj综合】贪|污排名【搜索二叉树】
  20. 计算机考试运用的数学知识点,计算器的使用知识点

热门文章

  1. u盘安装linux7详细步骤,U盘安装CentOS 7的方法实例步骤介绍
  2. Hello! ImageNet ILSVRC 2012!
  3. SpringBoot+Vue+虹软(ArcSoft) 的一个在线人脸识别Web系统,可通过调用笔记本摄像头或者网络摄像头实时的进行人脸识别。
  4. 【干货分享】流程DEMO-费用报销
  5. 清洁机器人规划控制方案
  6. javascript迭代器
  7. 让HTTPS简要易懂
  8. IFNULL基本用法
  9. SpringBoot整合MongoDB以及副本集、分片集群的搭建
  10. canpcb阻抗_克服CAN设计挑战:CAN信号终端电阻篇