Python批量修改文件内容操作

python脚本

Posted by Carlos on July 31, 2023

前言

在实际的编程开发中,我们经常遇到需要批量修改多个文件的情况。这可能是由于重构代码、更改文件命名规则、更新文件内容等多种原因引起的。手动一个一个修改文件是非常繁琐且容易出错的,因此编写一个Python脚本来自动完成这个任务是一个不错的选择。 本文介绍了如何使用Python批量修改文件内容的操作,包括对文件进行更名、添加特定内容以及更新指定内容等操作。

准备工作

在开始之前,你需要确保以下几点:

  • 安装好 Python 解释器。
  • 拥有待处理的文件或文件夹。

方法介绍

批量对文件指定内容进行更新

该方法会遍历指定路径下的所有文件,判断文件内容中是否包含特定字符串,并将其替换为新的字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def updata_all_files(directory_path):
    '''

    :param directory_path: 指定路径
    :return: 更改文件信息
    '''
    for root, dirs, files in os.walk(directory_path):
        # print(f'当前目录{root}')

        if len(files) > 0:
            # 打印子目录文件名称
            # print("子目录文件名称:")
            for file_name in files:
                file_path = os.path.join(root, file_name)

                file_path = convert_windows_path(file_path)

                # 读取文件内容
                with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                    lines = f.readlines()

                    # 需要更新的内容
                    up_da = 'header-img: img/post-bg-dpdata.jpg'
                    nw_da = 'header-img: img/post-bg-updata.jpg'

                    # 遍历每一行,检查是否包含目标字符串
                    for i in range(len(lines)):
                        if up_da in lines[i]:
                            lines[i] = lines[i].replace(up_da, nw_da)
                            print(f'更新成功:{file_name} 内容:{lines[i]}')
                            break

                    # 将修改后的内容写回文件
                    with open(file_path, 'w',encoding='utf-8', errors='ignore') as file:
                        file.writelines(lines)

对博客文件做初始化操作

由于我的博客网址需要展示博客文章的话需要对文件内容和文件名的格式有要求,下面我们就可以根据上述代码进行修改来满足以下要求:

格式要求

  1. 文章抬头设置
1
2
3
4
5
6
7
8
9
10
11
12
13
---
ifupdate: false #是否需要更新配合初始化代码使用
layout: post     
title: Jekyll-博客模板	#文章标题
subtitle: 模板	#文章副标题
date: 2023-04-03	#文章日期
author: Carlos	#作者
header-img: img/bg-cook.jpg	#文章 head 图片
catalog: true	
tags:	#  网页 tags 标签
 - 博客模板
 - 博客入门	
---
  1. 文件名称和路径设置
    • 文件名称需要设置为 yyyy-MM-dd-文件名格式。格式不正确jekyll将不会解析该md文件

博客文章初始化代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""
@author:carlos
@file: test.py
@time: 2023/7/21  21:12
"""
import datetime
import random
import os

def updata_file_name(file_path,date,file_name):
    '''

    :param file_path: 文件地址
    :param date: 日期
    :param updata_name: 文件名
    :return: 更新后的文件名
    '''

    # 拼接名称
    splice_name = str(date) + '-' + str(file_name)

    # 文件更名
    new_file_path = os.path.join(os.path.dirname(file_path), splice_name)
    os.rename(file_path, new_file_path)

    print(f'文件抬头成功: {splice_name}')


def convert_windows_path(windows_path):
    '''

    :param windows_path: window下的路径
    :return: 返回一个可运行的格式
    '''
    # 将反斜杠替换为正斜杠
    python_path = windows_path.replace("\\", "/")

    # 如果路径是以盘符开头的绝对路径,则添加前缀 r"\\"
    if python_path.startswith("\\"):
        python_path = "r" + python_path

    return python_path

def get_date():
    '''
    :return: 返回一个随机日期值 格式 "%Y-%m-%d"
    '''
    # 获取当前日期
    current_date = datetime.datetime.now()

    # 随机生成100-1000之间的天数
    random_days = random.randint(30, 500)

    # 计算新日期
    new_date = current_date - datetime.timedelta(days=random_days)

    # 格式化日期为"yyyy-mm-dd"
    formatted_date = new_date.strftime("%Y-%m-%d")

    return formatted_date

def add_content_to_file(file_path,file_name, parent_dir_name, grandparent_dir_name):
    '''

    :param file_path: 文件地址
    :param file_name: 文件名
    :param parent_dir_name: 父目录
    :param grandparent_dir_name: 爷爷目录
    :return: 按模板更新好的md文件
    '''


    # 获取随机时间格式化日期为"yyyy-mm-dd"
    # date=datetime.datetime.now().strftime("%Y-%m-%d")
    date=get_date()


    # 读取文件内容
    file_path=convert_windows_path(file_path)

    with open(file_path, 'r', encoding='utf-8',errors='ignore') as f:
        lines = f.readlines()
        # print(file_path)

    # 判断前五行是否包含指定内容
    if not any('ifupdate: false' in line for line in lines[:5]):
        # 添加指定内容
        content = f'---\n' \
        f'ifupdate: false\n' \
        f'layout: post\n' \
        f'title: {file_name.split(".m")[0]}\n' \
        f'subtitle: {parent_dir_name}\n' \
        f'date: {date}\n' \
        f'author: Carlos\n' \
        f'header-img: img/bg-cook.jpg\n' \
        f'catalog: true\n' \
        f'tags:\n' \
        f' - {grandparent_dir_name}\n'  \
        f'---\n'


        # 首行和末行添加(如果你在Markdown文件中使用了Liquid模板语法,需要使用和标记来避免Liquid解析其中的内容)
        tail_line, head_line = '', ''
        lines.insert(0, tail_line)
        lines.append(head_line)

        # 首行添加(设置模式文本内容)
        lines.insert(0, content)


        # 写入更新后的内容到文件
        with open(file_path, 'w',encoding='utf-8', errors='ignore') as f:
            f.writelines(lines)

        # 更新文件名
        updata_file_name(file_path=file_path,date=date,file_name=file_name)

def init_all_files(directory_path):
    '''

    :param directory_path: 指定路径
    :return: 初始化文件属性
    '''

    for root, dirs, files in os.walk(directory_path):
        # print(f'当前目录{root}')

        if len(files) > 0:
            # 打印子目录文件名称
            # print("子目录文件名称:")
            for file_name in files:

                parent_dir_name = os.path.basename(root)
                grandparent_dir_name = os.path.basename(os.path.dirname(root))

                if '_posts' in parent_dir_name  :
                    parent_dir_name=''
                    grandparent_dir_name='未定义标签'
                if '_posts' in grandparent_dir_name:
                    grandparent_dir_name = '未定义标签'

                # print(f"文件名: {file_name}")
                # print(f"父目录名称: {parent_dir_name}")
                # print(f"爷目录名称: {grandparent_dir_name}")
                # print()

                if  file_name.endswith('.md') and not file_name[0].isdigit():

                    # 拼接文件路径
                    file_path = os.path.join(root, file_name)

                    add_content_to_file(file_path, file_name, parent_dir_name, grandparent_dir_name)  # 添加内容到文件

if __name__=='__main__':

    #当前路径下
    directory_path = os.getcwd()
    # 指定目录路径
    directory_path = r'C:\Users\carlos\Desktop\PycharmProjects\carlos_blog\github\carlos-github\_posts'

    # 初始化文件方法
    init_all_files(directory_path)

    #更新文件方法
    # updata_all_files(directory_path)

完成以上设置后,你可以保存并运行脚本。脚本会自动遍历指定路径下的所有文件,并根据需要进行相应的操作。你可以根据实际需求选择只执行初始化文件属性的方法或者更新文件信息的方法。 注意:在运行脚本之前,请确保你已经备份了相关文件,以防止意外修改导致数据丢失。

结语

通过使用Python批量修改文件内容的操作,我们可以大大提高文件操作的效率,减少手动操作的繁琐和错误。希望本文对你有所帮助,祝你编程愉快!