10.组织文件
1)shutil模块
复制文件和文件夹 copy() copytree()
文件和文件夹的移动 move()
永久删除文件和文件夹
os.unlink() 删除文件
os.rmdir() 删除空目录
shutil.rmtree() 删除目录树型,不能删除文件
os.glob() 得到路径下的文件列表
用send2trash模块安全删除,发送到垃圾箱
2)遍历目录树
os.walk() 遍历目录树。(经常用到)
测试程序:test_1001.py
import os
for folderName,subfolders,filenames in os.walk('d:\\temp\\waffle'):
print('The curent folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': ' + filename)
print(' ')
3)用zipfile模块压缩文件
读取ZIP文件
ZipFile() 打开一个压缩文件
namelist() 读文件列表
getinfo() 读指定文件的信息,file_size compress_size
close() 关闭压缩文件
从ZIP中解压缩
extractall() 全部解压缩
extract() 解压缩指定文件
创建一个ZIP文件
write() ZIP_DEFLATED
添加一个目录树到文件里
测试程序:test_1002.py
import os
import zipfile
def zip_dir(dir_path, zip_file_path):
zipf = zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(dir_path):
for file in files:
file_path = os.path.join(root, file)
file_in_zip_path = os.path.relpath(file_path, os.path.dirname(dir_path))
zipf.write(file_path, file_in_zip_path)
# 使用例子
dir_to_compress = 'd:/temp/waffle'
zip_file_name = 'waffle.zip'
zip_dir(dir_to_compress, zip_file_name)
4)项目:将美式日期的文件重命名为欧式日期
测试程序:test_1003.pys (原书程序有错误,会将日期识别成月份)。
#! python3
# renameDates.py - Renames filenames with American MM-DD-YYY date format to European DD-MM-YYYY.
import shutil,os,re
# 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)
# Loop over the files in the working directory.
for amerFilename in os.listdir('.'):
mo = datePattern.search(amerFilename)
# Skip files withou 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(f'Renaming "{amerFilename}" to "{euroFilename}"...')
shutil.move(amerFilename,euroFilename)
5)项目:将一个文件夹备份到ZIP文件
测试程序:test_1004.py
#! 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(f'Createing {zipFilename}...')
backupZip = zipfile.ZipFile(zipFilename ,'w')
for foldername ,subfolders,filenames in os.walk(folder):
print(f'Adding files in {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 back up the backp ZIP files
backupZip.write(os.path.join(foldername,filename))
backupZip.close()
print('Done.')
backupToZip('d:\\temp\\waffle')