【python】一些常用的小脚本

目录

找到指定后缀的文件列表

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

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编码。

python 复制代码
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语言使用 // 和 /* */ 来注释,调用方式如下:

python 复制代码
del_comm("main.c","//",["/*","*/"])
python 复制代码
# 删除所有注释
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[1],index)
        if(index>=0 and index_end>index):
            text_out+= text[index_start:index]
            index_start=index_end+len(blok_comm[1])
        else:
            text_out+=text[index_start:]
            break
    with open(file,mode="w+",encoding="utf-8") as f:
        f.write(text_out)
        

去除过多的空白字符

python 复制代码
def simplified(text:str):
  '''
  返回一个新字符串,去除过多的空白字符
  '''
  space=['\t', '\n', '\v', '\f', '\r',  ' ']

  r=""
  start=0
  is_empty=False
  while text[start] in space:
    start+=1
  for i in range(start,len(text)):
    if text[i] in space:
      is_empty=True
    else:
      if(is_empty==True):
        r+=" "
        is_empty=False
      r+=text[i]
  return r
相关推荐
kaoshi100app6 分钟前
2026年注册安全工程师报考条件解读
开发语言·人工智能·职场和发展·学习方法
是三好8 分钟前
java集合
java·开发语言
凯子坚持 c9 分钟前
Qt常用控件指南(5)
开发语言·数据库·qt
weixin_BYSJ198711 分钟前
django农作物批发交易系统--附源码24008
java·javascript·spring boot·python·django·flask·php
Edward-tan11 分钟前
【玩转全栈】----Django模板语法、请求与响应
后端·python·django
foundbug99911 分钟前
MATLAB实现轴承刚度计算
开发语言·matlab
C++ 老炮儿的技术栈12 分钟前
CMFCEditBrowseCtrl用法一例
c语言·开发语言·c++·windows·qt·visual studio code
Three~stone12 分钟前
Matlab R2024b 保姆级安装教程(附:解决win10问题)
开发语言·算法·matlab
硕博计算机毕设指导15 分钟前
【大数据毕设全套源码+文档】Django基于大数据技术的智慧居家养老服务平的设计与实现(丰富项目+远程调试+讲解+定制)
大数据·python·信息可视化·django·毕业设计·课程设计
ytttr87315 分钟前
基于MATLAB的一维对流扩散方程数值求解
开发语言·算法·matlab