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
轉(zhuǎn)換文件編碼
示例為把gb2312編碼的文件轉(zhuǎn)化為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)
刪除文件注釋
輸入文件名,行注釋標(biāo)簽,塊注釋標(biāo)簽,生成刪除注釋后的文件保存并覆蓋原文件。
例如C語言使用 // 和 /* */ 來注釋,調(diào)用方式如下:
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): ''' 返回一個(gè)新字符串,去除過多的空白字符 ''' 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
到此這篇關(guān)于python 一些常用的小腳本的文章就介紹到這了,更多相關(guān)python 常用腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)百度OCR圖片識別過程解析
這篇文章主要介紹了python實(shí)現(xiàn)百度OCR圖片識別過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01關(guān)于Qt6中QtMultimedia多媒體模塊的重大改變分析
如果您一直在 Qt 5 中使用 Qt Multimedia,則需要對您的實(shí)現(xiàn)進(jìn)行更改。這篇博文將嘗試引導(dǎo)您完成最大的變化,同時(shí)查看 API 和內(nèi)部結(jié)構(gòu)2021-09-09python3+PyQt5 實(shí)現(xiàn)Rich文本的行編輯方法
今天小編就為大家分享一篇python3+PyQt5 實(shí)現(xiàn)Rich文本的行編輯方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python數(shù)據(jù)集庫Vaex秒開100GB加數(shù)據(jù)
這篇文章主要為大家介紹了Python數(shù)據(jù)集庫Vaex秒開100GB加數(shù)據(jù)實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06