python 一些常用的小腳本
更新時間:2024年04月02日 09:30:33 作者:明月清風舊
本文主要介紹了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","http://",["/*","*/"])
# 刪除所有注釋 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)
去除過多的空白字符
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
到此這篇關于python 一些常用的小腳本的文章就介紹到這了,更多相關python 常用腳本內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關文章
關于Qt6中QtMultimedia多媒體模塊的重大改變分析
如果您一直在 Qt 5 中使用 Qt Multimedia,則需要對您的實現(xiàn)進行更改。這篇博文將嘗試引導您完成最大的變化,同時查看 API 和內部結構2021-09-09python3+PyQt5 實現(xiàn)Rich文本的行編輯方法
今天小編就為大家分享一篇python3+PyQt5 實現(xiàn)Rich文本的行編輯方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06