【python】一些常用的小脚本

找到指定后缀的文件列表

找到指定后缀的文件,返回找到的文件路径列表,会递归文件夹。

import os



# 找到指定后缀的文件
def find_type(path:str,fix:str):
    dlist=os.listdir(path)
    file_list=[]
    for i in dlist:
        ps=os.path.join(path, i)
        if os.path.isdir(ps):
            file_list+=find_type(ps,fix)
        else:
            if(ps[-len(fix):]==fix):
                file_list.append(ps)
    return file_list

转换文件编码

示例为把gb2312编码的文件转化为utf8编码。

def conv(file:str):
    s=""
    try:
        with open(file,encoding="gb2312") as f:
            s=f.read()
        os.remove(file)
        with open(file,mode="w+",encoding="utf-8") as f:
            f.write(s)
    except Exception as e:
        print("conv failed",file)

删除文件注释

输入文件名,行注释标签,块注释标签,生成删除注释后的文件保存并覆盖原文件。
例如C语言使用 // 和 /* */ 来注释,调用方式如下:

del_comm("main.c","//",["/*","*/"])
# 删除所有注释
def del_comm(file:str,line_comm:str,blok_comm:list[str]):
    text=""
    try:
        with open(file,encoding="utf-8") as f:
            lines=f.readlines()
    except Exception as e:
        print("decode failed",file)
        return
    for i in range(len(lines)):
        index=lines[i].find(line_comm)
        if(index>=0):
            lstr=lines[i][:index]
        else:
            lstr=lines[i].rstrip()
        if(len(lstr.strip())>0):
            text+=lstr+'\n'
        elif(text[-2:]=='\\\n'):
            text+='\n'
    index_start=0
    text_out=""
    while True:
        index=text.find(blok_comm[0],index_start)
        index_end=text.find(blok_comm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值