Python 项目实践:文件批量处理

Python 项目实践:文件批量处理

文章目录

  • [Python 项目实践:文件批量处理](#Python 项目实践:文件批量处理)
      • [一 背景](#一 背景)
      • [二 发现问题](#二 发现问题)
      • [三 分析问题](#三 分析问题)
      • [四 解决问题](#四 解决问题)
        • [1 找到所有文件](#1 找到所有文件)
        • [2 找到文件特定字段](#2 找到文件特定字段)
        • [3 找出复杂的字符串](#3 找出复杂的字符串)
        • [4 替换目标字符串](#4 替换目标字符串)
        • [5 验证文件是否正确](#5 验证文件是否正确)
      • [五 总结](#五 总结)
      • [六 完整代码示例](#六 完整代码示例)
      • [七 源码地址](#七 源码地址)

本项目旨在通过 Python 编程实现对大量文件的批量处理。假设我们有 1000 个文件需要修改特定字段,例如将 yourpython.github.io 替换为 yourpython.com 。通过结合 Python 的文件管理、循环控制、正则表达式等知识,逐步解决问题。首先,通过 os.listdir() 遍历文件,利用正则表达式 re.findall() 找到需要替换的字段。然后,选择替换方案,将修改后的内容保存到新文件中,以保持原始文件不变。该项目展示了从发现问题、分析需求,到编写解决方案的完整过程,是实际应用 Python 知识的一个良好示例。

一 背景

让我们一起开展一个小项目,把之前学到的知识实际应用起来。根据自己的学习情况,预备课程可以选择跳过。

预备课

Python 文件与目录管理:操作、管理与检验详解
Python for 和 while 循环:掌握循环控制的基本操作
Python 文件读写操作详解:从创建到编码处理.md
Python 正则表达式详解:从基础匹配到高级应用

本章主要涉及功能

找到所有文件 找到文件特定字段 替换
os.listdir() re.findall() os.path.join()
os.path.join() os.path.join() re.sub()
string.startswith()

二 发现问题

假如要处理大量文件,比如 1000 个文件,需要替换其中的特定字符,比如把 yourpython.github.io 改成 yourpython.com

三 分析问题

需求分析,要满足以下三点:

  • 遍历所有的文本文件
  • 找到文件中特定字段
  • 替换掉这些特定字段

四 解决问题

1 找到所有文件

这里需要 Python 文件与目录管理:操作、管理与检验详解 这章的知识点。

python 复制代码
print(os.listdir("yourfiles"))
2 找到文件特定字段

这里需要 Python for 和 while 循环:掌握循环控制的基本操作Python 文件读写操作详解:从创建到编码处理.md 这两章的知识点。

python 复制代码
    for filename in os.listdir("yourfiles"):
        file_path = os.path.join("yourfiles", filename)
        with open(file_path, "r") as f:
            print(file_path, ": ", f.read())
3 找出复杂的字符串

这里需要 Python 正则表达式详解:从基础匹配到高级应用 这章的知识点。

python 复制代码
    string = "这是我的主页 https://mofanpy.com, 这个 www.mofanpy.com 有很多 mofan 教你机器学习和 python 语言的教学"
    res = re.findall(r"(https://)?(mofanpy.com)", string)
    for r in res:
        print(r[1])
4 替换目标字符串

这里有二种方案:

  • 在原文本上替换,并覆盖原文本的内容。
  • 复制出一个新的文件,将原文本替换过的文字拷贝到新文件中,原文件不改变。

这里选择方案二。

python 复制代码
    for filename in os.listdir("yourfiles"):
        file_path = os.path.join("yourfiles", filename)
        with open(file_path, "r") as f1:
            string = f1.read()
            new_string = re.sub(r"yourpython.github.io", "yourpython.com", string)
            with open(os.path.join("yourfiles", "new_" + filename), "w") as f2:
                f2.write(new_string)
5 验证文件是否正确
python 复制代码
    for filename in os.listdir("yourfiles"):
        if filename.startswith("new_"):
            continue
        file_path = os.path.join("yourfiles", "new_" + filename)
        with open(file_path, "r") as f:
            print(file_path, ": ", f.read())

五 总结

尽管这个任务看起来很简单,但其实包含了对项目的一些深度思考,比如如何发现问题、分析问题、解决问题 。通过之前那个 简单的计算器项目 以及当前这个实践,大家对使用 Python 开发项目应该有了更深入的理解。好了,到了这个阶段,大家已经可以尝试独立完成一些简单的项目了。接下来的课程将致力于进一步提升你的技能,而且内容会更加丰富精彩。

六 完整代码示例

python 复制代码
# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import os
import re


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press ⌘F8 to toggle the breakpoint.
    # 项目实践 文件批量处理
    # 预备课:
    # 文件目录管理
    # for 和 while 循环
    # 读写文件
    # 正则表达式

    # 主要涉及功能
    # 找到所有文件
    # os.listdir()
    # os.path.join()
    # 找到文件特定字段
    # re.findall()
    # os.path.join()
    # 替换
    # os.path.join()
    # re.sub()
    # string.startswith()

    # 我遇到的问题 ,我们要处理大量文件 比如 1000 个文件,需要替换其中的特定字符,
    # 比如把 yourpython.github.io 改成 mofanpy.com

    # 分析问题
    # 遍历所有的文本文件
    # 找到文件中特定字段
    # 替换掉这个特定字段

    # 找到所有文件,文件目录管理
    print(os.listdir("yourfiles"))

    # 找到文件特定字段,for 和 while 循环,读写文件
    for filename in os.listdir("yourfiles"):
        file_path = os.path.join("yourfiles", filename)
        with open(file_path, "r") as f:
            print(file_path, ": ", f.read())

    # 找出复杂的字符串,正则表达式
    string = "这是我的主页 https://mofanpy.com, 这个 www.mofanpy.com 有很多 mofan 教你机器学习和 python 语言的教学"
    res = re.findall(r"(https://)?(mofanpy.com)", string)
    for r in res:
        print(r[1])

    # 替换,有二种方案
    # 在原文本上替换,并覆盖原文本的内容;
    # 复制出一个新的文件,将原文本替换过的文字拷贝到新文件中,原文件不改变。
    # 这里选择方案二
    for filename in os.listdir("yourfiles"):
        file_path = os.path.join("yourfiles", filename)
        with open(file_path, "r") as f1:
            string = f1.read()
            new_string = re.sub(r"yourpython.github.io", "yourpython.com", string)
            with open(os.path.join("yourfiles", "new_" + filename), "w") as f2:
                f2.write(new_string)

    # 查看文件是否正确
    print()
    for filename in os.listdir("yourfiles"):
        if filename.startswith("new_"):
            continue
        file_path = os.path.join("yourfiles", "new_" + filename)
        with open(file_path, "r") as f:
            print(file_path, ": ", f.read())


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('文件批量处理')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

复制粘贴并覆盖到你的 main.py 中运行,运行结果如下。

nginx 复制代码
Hi, 文件批量处理
['c.txt', 'b.txt', 'a.txt', 'd.txt']
yourfiles/c.txt :  yourpython.github.io is my favorite site, please have a look.
yourfiles/b.txt :  this is a page in yourpython.github.io, please have a look.
yourfiles/a.txt :  I have an apple, I have a pen
yourfiles/d.txt :  what is my favorite site, please have a look of yourpython.github.io.
mofanpy.com
mofanpy.com

yourfiles/new_c.txt :  yourpython.com is my favorite site, please have a look.
yourfiles/new_b.txt :  this is a page in yourpython.com, please have a look.
yourfiles/new_a.txt :  I have an apple, I have a pen
yourfiles/new_d.txt :  what is my favorite site, please have a look of yourpython.com.

七 源码地址

代码地址:

国内看 Gitee文件批量处理.py

国外看 GitHub文件批量处理.py

引用 莫烦 Python

相关推荐
captain3761 分钟前
TCP网络编程:ServerSocket与Socket详解
服务器·网络·tcp/ip
可乐鸡翅yeah_6 分钟前
hls.js 播放质量埋点实战,采集卡顿、起播、错误指标定位线上用户问题
开发语言·前端·javascript·ecmascript·音视频·m3u8·音视频在线播放
szarron23 分钟前
RF Demo Kit|NanoVNA 射频演示测试板完整上手教程,滤波器、衰减器、SOLT 校准学习板
开发语言·人工智能·学习·php·射频工程·频谱仪
边境悍匪34 分钟前
蜗牛学苑 Java 智能体学习 Day39|SpringAI 会话存储、Function‑Call 工具调用、MCP 思维导图复盘
java·开发语言·spring boot·学习·阿里云
ellenwan202635 分钟前
看到“最新 AI 量化学习”时,先让表达变清楚
人工智能·python
万物智能信息科技1 小时前
RK3568 的多路显示移植—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
linux·开发语言·华为·开源·harmonyos
蓝悦无人机1 小时前
Qt Design Studio(QDS)4.8.2项目文件结构详解
开发语言·qt·qt creator·qds·项目文件结构·qtc
新时代牛马1 小时前
Linux 磁盘管理:分区、文件系统、挂载与扩容
linux·运维·服务器
yxlalm1 小时前
4.java秒杀项目第四课-后端商品后台接口
java·开发语言
海宇数据2 小时前
零信任架构实战:基于海宇柠檬查出险-登记证构建自动化残值评估网关
人工智能·python·架构·自动化