Find the list of files with the specified suffix
Find the file with the specified suffix and return the found file path list, which will recurse the folder.
import os # Find the file with the specified suffixdef find_type(path:str,fix:str): dlist=(path) file_list=[] for i in dlist: ps=(path, i) if (ps): file_list+=find_type(ps,fix) else: if(ps[-len(fix):]==fix): file_list.append(ps) return file_list
Convert file encoding
The example is to convert a gb2312-encoded file into an utf8-encoded file.
def conv(file:str): s="" try: with open(file,encoding="gb2312") as f: s=() (file) with open(file,mode="w+",encoding="utf-8") as f: (s) except Exception as e: print("conv failed",file)
Delete file comments
Enter the file name, line comment label, and block comment label, generate the file after deletion comment and save it and overwrite the original file.
For example, C language uses // and /* */ to comment, and the call method is as follows:
del_comm("","//",["/*","*/"])
# Delete all commentsdef del_comm(file:str,line_comm:str,blok_comm:list[str]): text="" try: with open(file,encoding="utf-8") as f: lines=() 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(())>0): text+=lstr+'\n' elif(text[-2:]=='\\\n'): text+='\n' index_start=0 text_out="" while True: index=(blok_comm[0],index_start) index_end=(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: (text_out)
Remove too many whitespace characters
def simplified(text:str): ''' Return a new string, removing too many whitespace characters ''' 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
This is the end of this article about some commonly used small scripts in python. For more related python For more commonly used scripts, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!