百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

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

liuian 2025-06-30 17:56 16 浏览

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:

相关推荐

教你把多个视频合并成一个视频的方法

一.情况介绍当你有一个m3u8文件和一个目录,目录中有连续的视频片段,这些片段可以连成一段完整的视频。m3u8文件打开后像这样:m3u8文件,可以理解为播放列表,里面是播放视频片段的顺序。视频片段像这...

零代码编程:用kimichat合并一个文件夹下的多个文件

一个文件夹里面有很多个srt字幕文件,如何借助kimichat来自动批量合并呢?在kimichat对话框中输入提示词:你是一个Python编程专家,完成如下的编程任务:这个文件夹:D:\downloa...

Java APT_java APT 生成代码

JavaAPT(AnnotationProcessingTool)是一种在Java编译阶段处理注解的工具。APT会在编译阶段扫描源代码中的注解,并根据这些注解生成代码、资源文件或其他输出,...

Unit Runtime:一键运行 AI 生成的代码,或许将成为你的复制 + 粘贴神器

在我们构建了UnitMesh架构之后,以及对应的demo之后,便着手于实现UnitMesh架构。于是,我们就继续开始UnitRuntime,以用于直接运行AI生成的代码。PS:...

挣脱臃肿的枷锁:为什么说Vert.x是Java开发者手中的一柄利剑?

如果你是一名Java开发者,那么你的职业生涯几乎无法避开Spring。它如同一位德高望重的老国王,统治着企业级应用开发的大片疆土。SpringBoot的约定大于配置、SpringCloud的微服务...

五年后,谷歌还在全力以赴发展 Kotlin

作者|FredericLardinois译者|Sambodhi策划|Tina自2017年谷歌I/O全球开发者大会上,谷歌首次宣布将Kotlin(JetBrains开发的Ja...

kotlin和java开发哪个好,优缺点对比

Kotlin和Java都是常见的编程语言,它们有各自的优缺点。Kotlin的优点:简洁:Kotlin程序相对于Java程序更简洁,可以减少代码量。安全:Kotlin在类型系统和空值安全...

移动端架构模式全景解析:从MVC到MVVM,如何选择最佳设计方案?

掌握不同架构模式的精髓,是构建可维护、可测试且高效移动应用的关键。在移动应用开发中,选择合适的软件架构模式对项目的可维护性、可测试性和团队协作效率至关重要。随着应用复杂度的增加,一个良好的架构能够帮助...

颜值非常高的XShell替代工具Termora,不一样的使用体验!

Termora是一款面向开发者和运维人员的跨平台SSH终端与文件管理工具,支持Windows、macOS及Linux系统,通过一体化界面简化远程服务器管理流程。其核心定位是解决多平台环境下远程连接、文...

预处理的底层原理和预处理编译运行异常的解决方案

若文章对您有帮助,欢迎关注程序员小迷。助您在编程路上越走越好![Mac-10.7.1LionIntel-based]Q:预处理到底干了什么事情?A:预处理,顾名思义,预先做的处理。源代码中...

为“架构”再建个模:如何用代码描述软件架构?

在架构治理平台ArchGuard中,为了实现对架构的治理,我们需要代码+模型描述所要处理的内容和数据。所以,在ArchGuard中,我们有了代码的模型、依赖的模型、变更的模型等,剩下的两个...

深度解析:Google Gemma 3n —— 移动优先的轻量多模态大模型

2025年6月,Google正式发布了Gemma3n,这是一款能够在2GB内存环境下运行的轻量级多模态大模型。它延续了Gemma家族的开源基因,同时在架构设计上大幅优化,目标是让...

比分网开发技术栈与功能详解_比分网有哪些

一、核心功能模块一个基本的比分网通常包含以下模块:首页/总览实时比分看板:滚动展示所有正在进行的比赛,包含比分、比赛时间、红黄牌等关键信息。热门赛事/焦点战:突出显示重要的、关注度高的比赛。赛事导航...

设计模式之-生成器_一键生成设计

一、【概念定义】——“分步构建复杂对象,隐藏创建细节”生成器模式(BuilderPattern):一种“分步构建型”创建型设计模式,它将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建...

构建第一个 Kotlin Android 应用_kotlin简介

第一步:安装AndroidStudio(推荐IDE)AndroidStudio是官方推荐的Android开发集成开发环境(IDE),内置对Kotlin的完整支持。1.下载And...