一、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.copytree()复制整个文件夹,还有文件夹内的所有东西。
>>> 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'
3、永久删除文件和文件夹
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.当前文件夹中子文件夹的字符串的列表。
三、用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对象。
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()
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 添加、追加