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

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

itomcoil 2025-05-15 18:23 6 浏览

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:

相关推荐

Python字符串格式化:你真的会用吗?告别混乱代码,看这一篇就够

大家好!今天我们来聊聊Python中一个看似简单却暗藏玄机的操作——字符串格式化。你是不是还在用%s拼凑变量?或者写了无数个format()却依然被同事吐槽代码太“复古”?别急,这篇干货带你解锁三种神...

Python Unicode字符串编程实用教程

Unicode是现代文本处理的基础,本教程将介绍Python中的Unicode字符串处理,涵盖从基础概念到高级应用等。一、Unicode基础概念1.1Unicode与编码核心概念:Unicode:字...

殊途同归 python 第 6 节:字符串的使用

字符串作为Python的基础数据之一,以下是字符串的几种最常用情形,直接上代码1.声明字符串a="helloworld"b='竹杖芒鞋轻胜马,谁怕,一蓑烟雨任平生...

python爬虫字符串定位开始跟结束(find方法的使用)

python爬虫采集的时候会需要对采集的内容进行处理行为,处理什么?简单的说就是处理多余的HTML代码跟确定文章标题跟结尾,还有内容区间,方法如下:首先先是定位,我们先假设我们采集到了一批数据,数据里...

python 入门到脱坑 基本数据类型—字符串string

以下是Python字符串(String)的入门详解,包含基础操作、常用方法和实用技巧,适合初学者快速掌握:一、字符串基础1.定义字符串#单引号/双引号s1='hello's...

python字符串知识点总结

Python字符串知识点总结1.字符串基础字符串是不可变的序列类型可以用单引号(')、双引号(")或三引号('''或""")创建三引号...

在 Python 中使用 f-String 格式化字符串

在Python3.6中引入的f字符串提供了一种既简洁又可读的字符串格式新方法。f字符串的正式名称为格式化字符串文字,是以f或F为前缀的字符串,其中包含大括号内的表达式。这些表达式在...

零起点Python机器学习快速入门-4-3-字符串常用方法

Python中字符串的多种操作。包括去除字符串首尾的空格和特定字符、字符串的连接、查找字符在字符串中的位置、字符串之间的比较、计算字符串的长度、大小写转换以及字符串的分割。通过这些操作,我们可以对字...

Python 中 字符串处理的高效方法,不允许你还不知道

以下是Python中字符串处理的高效方法,涵盖常用操作、性能优化技巧和实际应用场景,帮助您写出更简洁、更快速的代码:一、基础高效操作1.字符串拼接:优先用join()代替+原因:join()预...

Python字符串详解与示例

艾瑞巴蒂字符串的干货来了,字符串是程序中最常见的数据类型之一,用来表示数据文本,下面就来介绍下字符串的特性,操作和方法,和一些示例来吧道友:1.字符串的创建在python中字符串可以永单引号(...

Python中去除字符串末尾换行符的方法

技术背景在Python编程中,处理字符串时经常会遇到字符串末尾包含换行符的情况,如从文件中读取每一行内容时,换行符会作为字符串的一部分被读取进来。为了满足后续处理需求,需要将这些换行符去除。实现步骤1...

表格编程之争:Python VS VBA?Excel用户:新编程语言才真香!

Python和VBA哪个更好用?Python和VBA是两种不同的编程语言,它们都有自己的特点和优缺点。在表格编程方面,VBA在Excel中的应用非常广泛,可以通过宏来实现自动化操作和数据处理,也可以通...

用Python把表格做成web可视化图表

Python中有一个streamlit库,Streamlit的美妙之处在于您可以直接在Python中创建Web应用程序,而无需了解HTML、CSS或JavaScrip,今天我们就用st...

使用 Python 在 PowerPoint 演示文稿中创建或提取表格

PowerPoint中的表格是一种以结构化格式组织和呈现数据的方法,类似于Excel或Word等其他应用程序中表格的使用方式。它们提供了一种清晰简洁的方式来显示信息,使您的受众更容易消化和理...

用python实现打印表格的方法

最近在做表格输出的任务,一般有两种方法实现在控制台打印,一种是根据表格的输出规则自己写代码实现,另外一种是安装python的第三方依赖包prettytable实现这个效果。方法1:根据表格规则写代码...