python 常用功能实现的函数

获取特定 文件 目录

def simple_walk(pat,is_dir=False,simple=False,file_end=False,file_top=False,copy_dirs=False,):
    '''
    walk的简单封装
    '''
    for f in walk(pat):
        target=f[2]
        if is_dir:
            target=f[1]
        for i in target:
            all=path.join(f[0],i)
            if file_end and path.isdir(f[0]) and next(walk(f[0]))[1]:
                break
            if copy_dirs:
                yield all.replace(pat+'\\','')
            elif not simple:
                yield (f[0],i)
            else:
                yield all
        if file_top:
            return
def get_files(**args):
    return simple_walk(pat=args['path'],is_dir=False,simple=args.get('simple',False),file_end= args.get('file_end',False),file_top= args.get('file_top',False))
def get_dirs(**args):
    return simple_walk(pat=args['path'],is_dir=True,simple=args.get('simple',False),file_end= args.get('file_end',False),file_top= args.get('file_top',False))    

解压文件

import zipfile
from pathlib import Path
class file_zip:
    root=''
    def __init__(self,root) -> None:
        self.root=root
    def compress_file(self):
        in_dir=Path(self.root)

        #验证是否已有压缩文件
        zipf_name="压缩-{}.zip".format(in_dir.name)
        zipf_path=in_dir.joinpath(zipf_name)
        if os.path.exists(zipf_path) :
            os.remove(zipf_path)
            # return zipf_path
        zipf=zipfile.ZipFile(zipf_path,'w')
        args_list=[i for i in get_files(path=in_dir,simple=True,file_top=True)]
        for i in args_list:
            file=Path(i)
            if file.suffix=='.zip':
                continue
            zipf.write(file,arcname='压缩文件/'+file.name)
        zipf.close()
        return zipf_path

    def extract_file(self):
        target_path=Path(self.root).joinpath('解压文件')
        if not target_path.exists():
            os.mkdir(target_path)

        args_list=[i for i in get_files(path=self.root,simple=True,file_top=True)]
        for i in args_list:
            zip_file=Path(i)
            if zip_file.suffix== '.zip':
                zipuf=zipfile.ZipFile(zip_file,'r')
                zipuf.extractall(target_path)
        zipuf.close()

root=r'C:\Users\xxx\Videos\out'
f=file_zip(root)
f.compress_file()
f.extract_file()

限时输入 适用于需要持续运行但用户又能中途输入信息控制程序方向
超时未输入获取默认值''空

from concurrent.futures import ThreadPoolExecutor,as_completed

def f(ar):
    desc,limit=ar
    r=input(desc+'({}):'.format(limit))
    return r

def input_limit(desc='限时输入:',limit=3):
    ar=desc,limit
    a=ThreadPoolExecutor(max_workers=1)
    task=[a.submit(f,ar)]
    try:
        for i in as_completed(task,timeout=limit):
            r=i.result()
            return r
    except:
        return ''

r=input_limit('暂停时间')

desc

python

desc

python
posted @ 2022-02-04 19:46  caiusxin  阅读(81)  评论(0)    收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css