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()