一、shutil模块
shutil
(或称为
shell
工具)模块中包含一些函数,让你在
Python
程序中复制、 移动、改名和删除文件。要使用 shutil
的函数,首先需要
import shutil
。
1、复制文件和文件夹
>>> import shutil, os
>>> os.chdir('C:\\')
>>> shutil.copy('C:\\spam.txt', 'C:\\delicious')
'C:\\delicious\\spam.txt'
>>> shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
'C:\\delicious\\eggs2.txt'
shutil.copy(source, destination)
1、将第一个参数复制到第二个参数处
2、如果第二个参数是个文件名,则重命名为第二个参数
3、返回的是复制过去后的路径
shutil.copytree()复制整个文件夹,还有文件夹内的所有东西。
shutil.copytree(source, destination)
,将路径
source
处的文件夹,包括它的所有文件和子文件夹,复制到路径 destination
处的文件夹。
>>> import shutil, os
>>> os.chdir('C:\\')
>>> shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
'C:\\bacon_backup'
1、如果文件夹不存在,则会新建一个文件夹
2、文件和文件夹的移动与改名
>>> import shutil
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'
注意:如果eggs文件夹中存在bacon.txt文件,则原来的文件就会被覆盖,所以需要注意。
shutil.move()方法和Linux中的mv方法一样,还可以重命名。
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt')
'C:\\eggs\\new_bacon.txt'
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs'
注意:构成目的地的文件夹必须已经存在,否则 Python 会抛出异常。
>>> shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')
Traceback (most recent call last):
File "C:\Python34\lib\shutil.py", line 521, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 3] The system cannot find the path specified:
'spam.txt' -> 'c:\\does_not_exist\\eggs\\ham'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')
File "C:\Python34\lib\shutil.py", line 533, in move
copy2(src, real_dst)
File "C:\Python34\lib\shutil.py", line 244, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Python34\lib\shutil.py", line 108, in copyfile
with open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\does_not_exist\\
eggs\\ham'
Python
在
does_not_exist
目录中寻找
eggs
和
ham
。它没有找到不存在的目录, 所以不能将 spam.txt
移动到指定的路径
3、永久删除文件和文件夹
利用
os
模块中的函数,可以删除一个文件或一个空文件夹。
利用
shutil
模块, 可以删除一个文件夹及其所有的内容。
•
用
os.unlink(path)
将删除
path
处的文件。
•
调用
os.rmdir(path)
将删除
path
处的文件夹。该文件夹必须为空,其中没有任 何文件和文件夹。
•
调用
shutil.rmtree(path)
将删除
path
处的文件夹,它包含的所有文件和文件夹都会被删除。
为了防止我们误删一些文件,我们可以将删除语句注释掉,用print打印出需要删除的文件,确认后再取消注释进行删除。
4、用send2trash模块安全地删除
shutil.rmtree()方法太狠,删除文件夹及内的所有文件与文件夹
因此诞生了比较温柔的第三方send2trash模块,它会将文件夹和文件发送到计算机的回收站,还是可以还原的。
import send2trash
baconFile=open('shy.txt','a')
baconFile.write('this is a text txt.')
baconFile.close()
send2trash.send2trash('shy.txt')
但是send2trash()方法不能释放磁盘空间,用os和shutil可以释放磁盘空间。
二、遍历目录树
os.walk()函数:可以遍历目录树
import os
for folderName, subfolders, filenames in os.walk('D:\\shy'):
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()函数被传入一个字符串值,即一个文件夹的路径。你可以在一个 for 循环语句中使用os.walk()函数,遍历目录树,就像使用 range()函数遍历一个范围的数字一样。不像 range(),os.walk()在循环的每次迭代中,返回 3 个值:
1.当前文件夹名称的字符串。
2.当前文件夹中子文件夹的字符串的列表。
3
.当前文件夹中文件的字符串的列表。
所谓当前文件夹,是指
for
循环当前迭代的文件夹。程序的当前工作目录,不会因为 os.walk()
而改变。
三、用zipfile模块压缩文件
1、读取zip文件
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.namelist()
['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
>>> spamInfo = exampleZip.getinfo('spam.txt')
>>> spamInfo.file_size
13908
>>> spamInfo.compress_size
3828
>>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo
.compress_size, 2))
'Compressed file is 3.63x smaller!'
>>> exampleZip.close()
ZipFile对象的namelist()方法:返回zip文件内的文件夹和文件名称。
这些名称可以传递给ZipFile对象的getinfo()方法,返回一个关于特定对象的ZipInfo对象。
ZipInfo
对象有自己的属性,诸如表示字节数的
file_size 和 compress_size
,它们分别表示原来文件大小和压缩后文件大小。
ZipFile
对象表示整个归档文件,而 ZipInfo
对象则保存该归档文件中每个文件的有用信息。
2、从 ZIP 文件中解压缩
ZipFile对象的extractall()方法:解压缩。
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip') # 使用zipfile模块的ZipFile()方法读取压缩文件,创建一个ZipFile文件对象。
>>> exampleZip.extractall() #调用ZipFile对象的extractall()方法,解压缩包
>>> exampleZip.close()
你可以向 extractall()传递的一个文件夹名称,它将文件解压缩到那个文件夹,而不是当前工作
目录。如果传递给
extractall()
方法的文件夹不存在,它会被创建。例如,如果你用exampleZip.extractall('C:\\ delicious')取代
处的调用,代码就会从
example.zip
中解压缩文件,放到新创建的 C:\delicious
文件夹中。
ZipFile对象的extract()方法:从zip文件中解压单个文件。
>>> exampleZip.extract('spam.txt') # 必须是namelist()中的一个
'C:\\spam.txt'
>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')# 解压到指定文件夹中 如果不存在会创建它
'C:\\some\\new\\folders\\spam.txt' # 返回值是解压缩后文件的绝对路径
>>> exampleZip.close()
3、创建和添加到ZIP文件
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()
写模式打开ZipFile对象,即添加第二个参数‘w’
ZipFile对象的write()方法传入一个路径,会压缩该路径所致的文件,第二个参数是压缩类型。
w 会覆写 a 添加、追加