列表格式显示

- 分类

广告招商中......
联系方式!

- 时间排序 更多...
    - 点击排序 更多...
      - 大小排序 更多...
        作者

         

        最近发布的软件 更多>>

        首页 >> >> >>python3_zipfile_创建压缩文件_读写注释 发布者:blog >> 本人发布的更多软件

        广告招商中...... 联系方式!

        python3_zipfile_创建压缩文件_读写注释 

        时间:2024-02-18 16:52:42      作者:blog     访问量:  
        ;开始下载地址

        #


        • ZipFile的 compression= 缺省是 ZIP_STORED(仅存储不压缩)。
          所以要指定为 ZIP_DEFLATED (zip算法),或 ZIP_LZMA (lzma算法,压缩率高,就是慢了点)

          • compresslevel= 要py3.7以上才支持。

        • 写入文件,可以用 write() ,或 writestr()

          • write() ,就不需要自己设置文件修改时间了。

        例子1,创建zip,写注释,改文件的mtime

        <pre class="highlighter-hljs" style="transition-duration: 0.2s; transition-property: background, font-size, border-color, border-radius, border-width, padding, margin, color; overflow: auto; margin: 10px auto; font-size: 13px; background-color: rgb(255, 255, 255);">import?osimport?timeimport?zipfile orgfilename=需要压缩的原始文件名fstat=os.stat(orgfilename)?#?获取文件修改时间bname=os.path.basename(orgfilename)?#去掉路径comment=This?is?a?test?comment.\n?This?is?line?2.?#限制65535个字节fzip=zipfile.ZipFile(orgfilename+.zip,w,compression=zipfile.ZIP_DEFLATED)?#py<=3.6#fzip=zipfile.ZipFile(orgfilename+.zip,w,compression=zipfile.ZIP_DEFLATED,compresslevel=6)?#py>=3.7fzip.comment=comment.encode(utf-8)??#?bytes,写入zip本身的comment.?无论什么时候写入,都是存在zip文件的末尾。with?open(orgfilename,rb)?as?fin: ????fzip.writestr(mydir/+bname,fin.read())?#?把文件压缩写入zip。加了一层目录mydir在zip中.finfo=fzip.getinfo(mydir/+bname)?#获取这个文件的info#?因为文件是通过writestr()写入的,所以文件修改时间需要自己设置。否则为当前时间。finfo.date_time=time.localtime(fstat.st_mtime)[0:6]?#?文件修改时间finfo.comment=comment.encode(utf-8)?#bytes,?写入对应文件的comment.实际存在文件的末尾。fzip.close()?#zip文件创建完成

        例子2,注释中写 json 格式

        import?json#zip文件的注释可以这么用COMM={}
        COMM[d1]=123COMM[f1]=3.25COMM[s1]=abcdefgcomment=json.dumps(COMM,indent=2)?#用indent好看点
        ?...
        fzip.comment=comment.encode(utf-8)??#?bytes,写入zip本身的comment

        例子3,读zip,读注释,解压文件

        import?jsonimport?zipfilefrom?io?import?BytesIO
        
        zipname=zip的文件名fzip=zipfile.ZipFile(zipname,r)?#打开zip文件comm=fzip.comment.decode(utf-8)?#?zip自身的注释,读取速度比较快print(===>?zip?comment:)print(comm)
        zipdata=json.loads(comm)?#?获取comment中的json数据print(===>?data?from?json:)print(repr(zipdata))
        
        names=fzip.namelist()??#获取压缩文件中的文件列表finfo=fzip.getinfo(names[0])?#读取第一个文件的属性print(===>?mtime?of?file:)print(%02d-%02d-%02d?%02d:%02d:%02d?%?finfo.date_time)?#文件修改时间print(===>?comment?of?file:)print(finfo.comment.decode(utf-8))?#文件的注释fout=BytesIO(fzip.read(names[0]))?#读取第一个文件内容,放入内存.?(也可以解压到磁盘去)fzip.close()
        ?...
        fout.close()



        本页Html网址:/htmlsoft/619345.html

        本页aspx网址:/soft.aspx?id=619345&bianhao=202402181652427436_77770&kind1=&kind2=

        最后访问时间:2024-03-17 12:03:40

        上一篇:如何解决Python Zipfile中的乱码

        下一篇:馈线商品销量

        增加   


        相关评论        新窗口打开查看评论