Python修改文件往指定行插入内容

本文介绍了一种批量修改Python文件中类属性的方法,通过匹配指定文本中的描述来为类增加一个名为core的新属性。该方法适用于需要对大量Python源代码进行统一修改的场景。

需求:批量修改py文件中的类属性,为类增加一个core = True新的属性

原py文件如下
a.py

class A():
    description = "abc"

现在有一个1.txt文本,内容如下,如果有py文件中的description跟txt文本中的一样,则增加core属性
1.txt

description = "abc"
description = "123"

实现思路:
1.需要遍历code目录下的所有py文件,然后读取所有行数内容保存到lines列表中
2.遍历每个文件的每一行,匹配1.txt中的description,如果匹配中,就返回行号
3.往lines列表中根据行号插入要增加的新属性
4.重新写回原文件,达到修改文件的目的

如果修改成功后,效果应该是这样的
a.py

class A():
    description = "abc"
    core = True

实现代码:

import os

original_folder = 'E:\\code\\'


core_list = []

count = 0

# if the description is in the current line
def isMatchDescription(line_buffer):
    global core_list

    # if not catch the core_list in global, reload it.
    if not core_list:
        with open("./core.txt","r") as f:
            core_list = f.readlines()

    # if match the core description
    for des in core_list:
        if line_buffer.strip() == des.strip():
            return True
    return False



def modifySignatures():
    for dirpath, dirnames, filenames in os.walk(original_folder):
        for filename in filenames:
            modifyFile(os.path.join(dirpath,filename))

def modifyFile(filename):

    global count
    #print "Current file: %s"% filename
    lines = []
    with open(filename,"r") as f:
        lines =  f.readlines()
        hit = 0

        # Enume every single line for match the description
        for index, line in enumerate(lines):
            if isMatchDescription(line):
                hit = index
                print hit
                print "Matched file:%s" % filename
                count+=1
        if hit > 0:
            lines.insert(hit-1,'    core = True\n')
        f.close()

    # Write back to file
    with open(filename,"w") as f:
        for line in lines:
            f.write(line)
        f.close()

if __name__ == '__main__':
    modifySignatures()
    print "Modified:%d"%count

代码中的lines.insert(hit-1,' core = True\n')这一行,hit代表目标py文件的description属性的行号,我之前用的是hit+1,但是后面发现有些文件出现了语法错误,原因是py文件中有些description的值太长,导致原文件使用了代码换行符\,如下:

a.py

class A():
    description = "abc\
    aaaaabbbbb"

这样的如果修改后就变成了

class A():
    description = "abc\
    core = True
    aaaaabbbbb"

为了避免这个bug,后面我才改成了hit-1

lines.insert(hit-1,' core = True\n')

这样修改的py文件后就是这样的效果

class A():
    core = True
    description = "abc\
    aaaaabbbbb"
Python 中向文件插入内容时,由于文件本身不支持直接插入操作,因此需要通过读取原有内容修改内容并重新写入的方式来实现。以下是几种常见的处理方式及示例代码: ### 1.文件开头插入 如果希望在文件的最开始位置插入内容,可以先读取整个文件内容,然后将新内容添加到最前面,并覆盖写回原文件。 ```python new_line = "这是要插入的第一\n" with open("example.txt", "r", encoding="utf-8") as file: content = file.read() with open("example.txt", "w", encoding="utf-8") as file: file.write(new_line + content) ``` ### 2.文件中间插入 如果要在特定号(例如第 2 )前插入内容,则可以逐读取文件内容,并在指定位置插入新的。 ```python insert_line_number = 2 new_line = "这是插入的新\n" with open("example.txt", "r", encoding="utf-8") as file: lines = file.readlines() lines.insert(insert_line_number - 1, new_line) with open("example.txt", "w", encoding="utf-8") as file: file.writelines(lines) ``` ### 3.文件末尾追加一 如果只需要在文件末尾添加一内容,可以直接使用 `open()` 函数的 `'a'` 模式[^1]。 ```python new_line = "这是追加的一\n" with open("example.txt", "a", encoding="utf-8") as file: file.write(new_line) ``` ### 注意事项 - 使用 `'w'` 模式会清空文件内容后再写入数据,因此在执插入操作时应避免误用。 - 如果文件较大,一次性读取全部内容可能会影响性能,建议采用逐处理的方式进优化。 - 插入操作本质上是读取原文件内容修改内容后重新写入的过程,因此无法避免 I/O 操作带来的性能开销。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值