[python]《Python编程快速上手:让繁琐工作自动化》学习笔记3

1. 组织文件笔记(第9章)(代码下载)

1.1 文件与文件路径
通过import shutil调用shutil模块操作目录,shutil模块能够在Python 程序中实现文件复制、移动、改名和删除;同时也介绍部分os操作文件的函数。常用函数如下:

函数用途备注
shutil.copy(source, destination)复制文件
shutil.copytree(source, destination)复制文件夹如果文件夹不存在,则创建文件夹
shutil.move(source, destination)移动文件返回新位置的绝对路径的字符串,且会覆写文件
os.unlink(path)删除path处的文件
os.rmdir(path)删除path处的文件夹该文件夹必须为空,其中没有任何文件和文件
shutil.rmtree(path)删除path处的文件夹包含的所有文件和文件夹都会被删除
os.walk(path)遍历path下所有文件夹和文件返回3个值:当前文件夹名称,当前文件夹子文件夹的字符串列表,当前文件夹文件的字符串列表
os.rename(path)path处文件重命名

1.2 用zipfile 模块压缩文件
通过import zipfile,利用zipfile模块中的函数,Python 程序可以创建和打开(或解压)ZIP 文件。常用函数如下:

函数用途备注
exampleZip=zipfile.ZipFile(‘example.zip’)创建一个ZipFile对象example.zip表示.zip 文件的文件名
exampleZip.namelist()返回ZIP 文件中包含的所有文件和文件夹的字符串的列表
spamInfo = exampleZip.getinfo(‘example.txt’)返回一个关于特定文件的ZipInfo 对象example.txt为压缩文件中的某一文件
spamInfo.file_size返回源文件大小单位字节
spamInfo.compress_size返回压缩后文件大小单位字节
exampleZip.extractall(path))解压压缩文件到path目录path不写,默认为当前目录
exampleZip.extract(‘spam.txt’, path)提取某一压缩文件当path目录path不写,默认为当前目录
newZip = zipfile.ZipFile(‘new.zip’, ‘w’)以“写模式”打开ZipFile 对象
newZip.write(‘spam.txt’, compress_type=zipfile.ZIP_DEFLATED)压缩文件第一个参数是要添加的文件。第二个参数是“压缩类型”参数
newZip.close()关闭ZipFile对象

2. 项目练习

2.1 将带有美国风格日期的文件改名为欧洲风格日期

# 导入模块
import shutil
import os
import re
# Renames filenames with American MM-DD-YYYY date format to European DD-MM-YYYY.

# 含美国风格的日期
# 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)

# 查找路径
searchPath='d:/'

for amerFilename in os.listdir(searchPath):
    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(searchPath)
    # 原文件名
    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)  # uncomment after testing
Renaming "d:\今天是06-28-2019.txt" to "d:\今天是28-06-2019.txt"...

2.2 将一个文件夹备份到一个ZIP 文件


import zipfile
import os


# 弄清楚ZIP 文件的名称
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))
    # 创建新ZIP 文件
    backupZip = zipfile.ZipFile(zipFilename, 'w')
    # TODO: Walk the entire folder tree and compress the files in each folder.
    print('Done.')

    # 提取文件目录
    # 一层一层获得目录
    # 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) + '_'
            # 判断文件是否是压缩文件
            if filename.startswith(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('image')
Creating image_1.zip...
Done.
Done.

2.3 选择性拷贝

编写一个程序,遍历一个目录树,查找特定扩展名的文件(诸如.pdf 或.jpg)。不论这些文件的位置在哪里,将它们拷贝到一个新的文件夹中。

import shutil
import os


def searchFile(path, savepath):
    # 判断要保存的文件夹路径是否存在
    if not os.path.exists(savepath):
        # 创建要保存的文件夹
        os.makedirs(savepath)
    # 遍历文件夹
    for foldername, subfolders, filenames in os.walk(path):
        for filename in filenames:
            # 判断是不是txt或者pdf文件
            if filename.endswith('txt') or filename.endswith('pdf'):
                inputFile = os.path.join(foldername, filename)
                # 保存文件路径
                outputFile = os.path.join(savepath, filename)
                # 文件保存
                shutil.copy(inputFile, outputFile)


searchFile("mytest", "save")

2.4 删除不需要的文件

编写一个程序,遍历一个目录树,查找特别大的文件或文件夹。将这些文件的绝对路径打印到屏幕上。


import os


def deletefile(path):
    for foldername, subfolders, filenames in os.walk(path):
        for filename in filenames:
            # 绝对路径
            filepath = os.path.join(foldername, filename)
            # 如果文件大于100MB
            if os.path.getsize(filepath)/1024/1024 > 100:
                # 获得绝对路径
                filepath = os.path.abspath(filepath)
                print(filepath)
                # 删除文件
                os.unlink(filepath)


deletefile("mytest")

2.5 消除缺失的编号

编写一个程序,在一个文件夹中,找到所有带指定前缀的文件,诸如spam001.txt,spam002.txt 等,并定位缺失的编号(例如存在spam001.txt 和spam003.txt,但不存在spam002.txt)。让该程序对所有后面的文件改名,消除缺失的编号。


import os
import re
# 路径地址
path = '.'
fileList = []
numList = []
# 寻找文件
pattern = re.compile('spam(\d{3}).txt')
for file in os.listdir(path):
    mo = pattern.search(file)
    if mo != None:
        fileList.append(file)
        numList.append(mo.group(1))

# 对存储的文件排序
fileList.sort()
numList.sort()

# 开始缺失的文件编号
# 编号从1开始
index = 1
# 打印不连续的文件
for i in range(len(numList)):
    # 如果文件编号不连续
    if int(numList[i]) != i+index:
        inputFile = os.path.join(path, fileList[i])
        print("the missing number file is {}:".format(inputFile))
        outputFile = os.path.join(path, 'spam'+'%03d' % (i+1)+'.txt')
        os.rename(inputFile, outputFile)
the missing number file is .\spam005.txt:
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值