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

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, os
for 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 os
for 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 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('.')
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, os
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))
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) + '_' # changed
if filename.startwith(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('\home\my-repo\pythonLearn')
426

被折叠的 条评论
为什么被折叠?



