python零碎知识汇总

hegangben
2025-05-27 / 0 评论 / 3 阅读 / 正在检测是否收录...

mb8rooww.png

https://p1.ssl.qhimg.com/t010d1433ef39d6d0cf.jpg

只获取当前目录下,剔除文件,只要文件夹名称

import os
dbtype_list = os.listdir(“sql_dir_war”)
for dbtype in dbtype_list:
    if os.path.isfile(os.path.join(sql_dir_war,dbtype)):
        dbtype_list.remove(dbtype)

sql_dir_war 是当前路径下文件夹的名字,如果直接是当前路径下可以输入
dbtype_list = os.listdir()

python实现在某本中某个关键词前插入一行

def  add_line_above(src_keyword,des_keyword,des_dir):
    logging.debug("\033[1;34m add_line_above \033[0m")
    for line in fileinput.input(des_dir,inplace=1):
        if src_keyword in line:
            print(des_keyword)
        print(line,end="")

python实现在某本中某个关键词后插一行

def  add_line_below(src_keyword,des_keyword,des_dir):
    logging.debug("\033[1;34m add_line_below \033[0m")
for line in fileinput.input(des_dir,inplace=1):
print(line,end="")
        if src_keyword in line:
            print(des_keyword)
        

python实现在某本中删除某两个个关键词之间的内容

def  delete_segment_exclude(src_keyword_begin,src_keyword_end,src_dir):
    line_begin = 0
    line_end = 0
    for line in fileinput.input(src_dir,inplace=0):
        if src_keyword_begin in line:
            line_begin = fileinput.filelineno()

        if src_keyword_end in line:
            line_end = fileinput.filelineno()

    temp_file=open(src_dir+"_temp",'w+')
    for line in fileinput.input(src_dir,inplace=0):
        cur_line = fileinput.filelineno()
        if(cur_line>line_begin)&(cur_line<line_end):
            continue
        else:
            temp_file.write(line)
    temp_file.close()
    shutil.move(src_dir+"_temp",src_dir)
0

评论 (0)

取消