• python tempfile 临时生成文件包


    import tempfile, os
    In [10]: a = tempfile.TemporaryDirectory()                                                                                                                                                                                                                               
    
    In [11]: print(a)                                                                                                                                                                                                                                                        
    <TemporaryDirectory '/var/folders/p5/1ct1qgn97y3bqgvls363hrj00000gn/T/tmpji97rhy5'>
    
    In [12]: print(a.name)                                                                                                                                                                                                                                                   
    /var/folders/p5/1ct1qgn97y3bqgvls363hrj00000gn/T/tmpji97rhy5
    
    In [13]: zip_path = os.path.join(a.name, 'n.zip')                                                                                                                                                                                                                        
    
    In [14]: print(zip_path)                                                                                                                                                                                                                                                 
    /var/folders/p5/1ct1qgn97y3bqgvls363hrj00000gn/T/tmpji97rhy5/n.zip  

    tempfile 生成的文件句柄是带有上下文管理,用完即销毁

    eg:

     temp = tempfile.TemporaryDirectory()
        temp2 = tempfile.TemporaryDirectory()
        zip_path = os.path.join(temp2.name, "n.zip")
        zip = zipfile.ZipFile(zip_path, 'w')
        for i in url_datas:
            f_name = "{}.{}".format(i['name'], download_type)
            logger.info('file_name:{}, download_url:{}'.format(f_name, i))
            local_path = os.path.join(temp.name, f_name)
            response_data_file = requests.get(i['download_url'], stream=True, headers=headers, timeout=6*10)
            with open(local_path, 'wb') as f:
                for chunk in response_data_file.iter_content(chunk_size=1024*500):
                    if chunk:
                        f.write(chunk)
            zip.write(local_path, f_name)
        zip.close()
  • 相关阅读:
    Kibana
    nginx
    Installing Node.js and Express on Ubuntu
    Boost test vs2013 fatal error C1001
    最小二乘法拟合直线
    RvmTranslator for Linux
    RvmTranslator7.1
    OpenCASCADE直线与平面求交
    OpenCASCADE点向平面投影
    RvmTranslator7.0-OBJ
  • 原文地址:https://www.cnblogs.com/tangda/p/12988912.html
Copyright © 2020-2023  润新知