无意间想到的一个需求,然后就顺手写了写,留下来,方便以后用

列表版:(基本没用,仅提供思路,字典版稍微改动可以直接用)

  大体需求:

    把重复的文件名进行改名,达到浏览器下载相同文件的效果
    下载完成后再把文件夹和目录名删掉

import os
import zipfile
import shutil
import re def make_zip(source_dir, output_filename):
zipf = zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_DEFLATED)
pre_len = len(os.path.dirname(source_dir))
for parent, dirnames, filenames in os.walk(source_dir):
for filename in filenames:
pathfile = os.path.join(parent, filename)
arcname = pathfile[pre_len:].strip(os.path.sep) # 相对路径
zipf.write(pathfile, arcname)
zipf.close() dir_name = "files"
os.makedirs(dir_name)
file_names = ["文件1","文件2","文件1","文件1","文件1","wenjian1"]
file_names_sorted = sorted(file_names)
file_new_names = []
prog = re.compile(r".*\((\d+)\)$")
for file_name in file_names_sorted:
if file_name in file_new_names:
if prog.match(file_new_names[-1]):
file_name = file_name + "(%s)" % (int(prog.match(file_new_names[-1]).group(1))+1)
else:
file_name = file_name + "(1)"
file_new_names.append(file_name) for file_new_name in file_new_names:
file_path = os.path.join(dir_name, file_new_name)
with open(file_path+'.py', mode="w", encoding="utf-8")as f:
f.write("print('hello world!')") shutil.rmtree("files")
os.remove("files")

字典版:
  关键问题:tornado提供下载,对重复的文件名进行重命名(和浏览器类似)

import os
import zipfile
import shutil
import re
import tornado.web class FileDownLoadHandler(tornado.web.RequestHandler):
def post(self, *args, **kwargs):
def make_zip(source_dir, output_filename):
zipf = zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_DEFLATED)
pre_len = len(os.path.dirname(source_dir))
for parent, dirnames, filenames in os.walk(source_dir):
for filename in filenames:
pathfile = os.path.join(parent, filename)
arcname = pathfile[pre_len:].strip(os.path.sep) # 相对路径
zipf.write(pathfile, arcname)
zipf.close() # dir_name和file_infos都应该从数据库取
dir_name = "新建文件夹"
os.makedirs(dir_name)
file_infos = [{'file_content': 'print("Hello World!")', 'file_name': '文件1'},
{'file_content': 'print("Hello World!")', 'file_name': '文件2'},
{'file_content': 'print("Hello World!")', 'file_name': '文件1'}]
print(file_infos)
file_infos_sorted = sorted(file_infos, key=lambda item: item["file_name"])
prog = re.compile(r".*\((\d+)\)$")
print(file_infos_sorted)
file_new_infos = []
file_names_set = set()
for file_info in file_infos_sorted:
if file_info["file_name"] in file_names_set:
if prog.match(file_new_infos[-1]["file_name"]):
file_info["file_name"] = file_info["file_name"] + "(%s)" % (
int(prog.match(file_new_infos[-1]["file_name"]).group(1)) + 1)
else:
file_info["file_name"] = file_info["file_name"] + "(1)"
else:
file_names_set.add(file_info["file_name"])
file_new_infos.append(file_info) for file_new_info in file_new_infos:
file_path = os.path.join(dir_name, file_new_info["file_name"])
with open(file_path + ".py", mode="w", encoding="utf-8")as f:
f.write(file_new_info["file_content"]) target_name = dir_name + ".zip"
make_zip(dir_name, target_name) # 打包加压缩 # 下载
self.set_header('Content-Type', 'application/octet-stream')
self.set_header('Content-Disposition', ('attachment; filename=%s' % target_name).encode("utf-8"))
buf_size = 4096
with open(target_name, "rb")as f:
while True:
data = f.read(buf_size)
if not data:
break
self.write(data)
self.finish() shutil.rmtree(dir_name)
os.remove(target_name)

才发现自己是真的菜,无意间问了一个java的同事,他们说Java可以直接写如zip流,然后找到了python的写入文件流的方式

def test_zip(self):
import zipfile, tempfile, os
try:
file_name = tempfile.mktemp(suffix=".zip") # mktemp方法慎用
with zipfile.ZipFile(file_name, 'w', zipfile.ZIP_DEFLATED) as zf:
for i in range(5):
zf.writestr("文件名%s" % i, """print('文件内容')""")
# 这里接着就是下载逻辑了,和上面的一样,就不重复写了
finally:
os.remove(file_name)

python打包压缩文件夹zip+组装文件夹的更多相关文章

  1. 【转】打包 压缩 命令tar zip

    https://www.cnblogs.com/centos2017/p/7896807.html tar语法 #压缩tar -czvf ***.tar.gztar -cjvf ***.tar.bz2 ...

  2. 打包 压缩 命令tar zip

    tar语法 #压缩tar -czvf ***.tar.gztar -cjvf ***.tar.bz2#解压缩tar -xzvf ***.tar.gztar -xjvf ***.tar.bz2 tar ...

  3. linux 学习笔记 显示压缩文件 gong.zip 的文件内容

    #zip -v gong zip zip info: xxx >删除压缩文件中俄smart.txt 文件 #zip -d gong.zip smart.txt deleting:smart.tx ...

  4. linux tar打包压缩排除某个目录或文件

    用tar打包时想剔除打包目录中的某个子目录或文件: 比如你想打包/home这个目录,但是/home/afish/目录和/home/www/afish.php文件你都不想打包,方法是: tar -zcv ...

  5. Linux常用命令2--用户问题、文件的打包压缩

    Linux常用命令 如何进行用户和群组的创建和更改 [1]groupadd:用于创建新的群组. 语法:groupadd [-option] 用户名:其常用参数有:-g groupadd -g 555 ...

  6. ICSharpCode.SharpZipLib工具压缩与解压缩zip文件

    using System; using System.Collections.Generic; using System.IO; using System.Text; using ICSharpCod ...

  7. webpack打包后不能调用,改用uglifyjs打包压缩

    背景: 项目基于原生js,没用到任何脚手架和框架,但也需要打包压缩. 项目的js中声明了一些全局变量 供其他js调用. 这时候如果用webpack打包,基于webpack特性,会嵌套一层大函数,会将j ...

  8. Python打包文件夹的方法小结(zip,tar,tar.gz等)

    本文实例讲述了Python打包文件夹的方法.分享给大家供大家参考,具体如下: 一.zip ? 1 2 3 4 5 6 7 8 9 10 11 import os, zipfile #打包目录为zip文 ...

  9. PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载

    文章转载自:https://my.oschina.net/junn/blog/104464 PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PH ...

随机推荐

  1. Docker + webpack 打包前端项目

    码云代码地址: https://gitee.com/caonimashi/docker_deployment_front_end    构建基础镜像: 1.下载一个 Apline Linux 操作系统 ...

  2. Redis进阶实践之十九 Redis如何使用lua脚本

    一.引言               redis学了一段时间了,基本的东西都没问题了.从今天开始讲写一些redis和lua脚本的相关的东西,lua这个脚本是一个好东西,可以运行在任何平台上,也可以嵌入 ...

  3. Beta 凡事预则立

    写在Beta冲刺前 关于组长是否重选的议题和结论 总体结论 组长无需更换 队内无人替代 理由 当前组长能够较好的号召和组织团队成员进行工作 当前组长能够对项目有合理的规划 当前组长被大家一致认可可以继 ...

  4. 网络1711c语言函数作业总结

    作业地址:https://edu.cnblogs.com/campus/jmu/JMUC--NE17111712/homework/1335 总结 1.评分细则 评分注意事项 代码规范问题依旧要重视, ...

  5. 安装QT5.02

    1.下载QT5 SDK 下载地址:http://qt-project.org/downloads. 2.安装QT5 下载完后,假设放在Download/,切换到该目录,输入:./qt-linux-op ...

  6. Linux下ip配置与网络重启

    ip配置 //以下ip配置重启失效 sudo ifconfig 192.168.1.1 sudo ifconfig 192.168.1.1 netmask 255.255.255.0 网络重启 //关 ...

  7. animation & @keyframes 实现loading效果

    效果图截图如下: 直接上代码: html <!DOCTYPE html> <html> <head> <meta charset="utf-8&qu ...

  8. 记一次SQL调优/优化(SQL tuning)——性能大幅提升千倍以上

    好久不写东西了,一直忙于各种杂事儿,恰巧昨天有个用户研发问到我一个SQL调优的问题,说性能太差,希望我能给调优下,最近有些懒,可能和最近太忙有关系,本来打算问问现在的情况,如果差不多就不调了,那哥们儿 ...

  9. python之路--day6--字符编码

    一.知识储备 cpu--控制和运算 内存--暂时存储cpu需要的数据 硬盘--永久保存数据2.文本编辑器的原理存储原理 1,启动文本编辑器 2,在编辑器上输入内容---此时输入内容还在内存上 3,保存 ...

  10. Service Worker和HTTP缓存

    很多人,包括我自己,初看Service Worker多一个Cache Storage的时候,就感觉跟HTTP长缓存没什么区别. 例如大家讲的最多的Service Worker能让网页离线使用,但熟悉H ...