【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
相关推荐
gf13211114 小时前
python_【更新已发送的消息卡片】
java·前端·python
java_logo4 小时前
轻量AI接口网关一键部署|calciumion/new-api Windows/Linux Docker 部署全教程
linux·人工智能·windows·one api·calciumion·ai网关部署·one api 部署
WL_Aurora4 小时前
Java字符输入全攻略
java·开发语言
keineahnung23454 小时前
PyTorch SymNode 為何找不到方法實作?──sizes_strides_methods 動態安裝機制解析
人工智能·pytorch·python·深度学习
2501_901006474 小时前
golang如何使用DTM分布式事务框架_golang DTM分布式事务框架使用方法
jvm·数据库·python
2501_901200534 小时前
Golang如何做Clean Architecture_Golang整洁架构教程【详解】
jvm·数据库·python
weixin_459753944 小时前
Go 中嵌入类型字段在派生结构体字面量中的初始化规则详解
jvm·数据库·python
CLX05054 小时前
HTML5中Mediastream实现摄像头画面实时捕获
jvm·数据库·python
茉莉玫瑰花茶4 小时前
LangGraph 拓展核心知识点
开发语言·windows·python
iAm_Ike4 小时前
PHP错误和异常如何处理_PHP错误与异常处理机制详解【详解】
jvm·数据库·python