在zip fi中编辑文件内容

2024-04-19 13:40:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多压缩档案,里面有文本文件。我需要找到并修改文件中的特定文本。不过,我还是用以下方法搜索了文件中的所有相关行:

import os
import zipfile
from glob import glob

files = []
pattern   = "*.zip"
for dir,_,_ in os.walk(r'X:\zips'):
    files.extend(glob(os.path.join(dir,pattern)))

    for file in  files:
        root = zipfile.ZipFile(file, "r")
        for name in root.namelist():
            for line in root.read(name).split("\n"):
                if line.find("keyword") >= 0:
                   print line

我知道我可以替换行内的关键字。但是,我怎样才能“就地”保存它而不把其他所有的文本文件都写到硬盘上,删除旧的zip并创建一个新的呢?在


Tags: 文件inimportforosdirlineroot
1条回答
网友
1楼 · 发布于 2024-04-19 13:40:26

如果不做一些底层的monkey业务,就无法做到这一点,而zipfile模块可能不支持这种业务。然而,这是可能的。在

首先简要介绍一下ZIP文件结构:

来自PKWare's ZIP file structure document

  [local file header 1]
  [encryption header 1]
  [file data 1]
  [data descriptor 1]
  . 
  .
  .
  [local file header n]
  [encryption header n]
  [file data n]
  [data descriptor n]
  [archive decryption header] 
  [archive extra data record] 
  [central directory header 1]
  .
  .
  .
  [central directory header n]
  [zip64 end of central directory record]
  [zip64 end of central directory locator] 
  [end of central directory record]

文件头看起来像:

^{2}$

中心目录结构如下:

    central file header signature   4 bytes  (0x02014b50)
    version made by                 2 bytes
    version needed to extract       2 bytes
    general purpose bit flag        2 bytes
    compression method              2 bytes
    last mod file time              2 bytes
    last mod file date              2 bytes
    crc-32                          4 bytes
    compressed size                 4 bytes
    uncompressed size               4 bytes
    file name length                2 bytes
    extra field length              2 bytes
    file comment length             2 bytes
    disk number start               2 bytes
    internal file attributes        2 bytes
    external file attributes        4 bytes
    relative offset of local header 4 bytes

    file name (variable size)
    extra field (variable size)
    file comment (variable size)

每个文件有一个CRC和每个文件的大小,中央目录中也有一个CRC和大小。因此,要修改一个文件-取决于您对该文件的实际操作,文件大小很可能会更改,CRC也会在99%的时间内更改

这意味着在之后的每个文件都必须在该文件中上移,从而改变整个归档文件的大小。在

您可以通过不压缩该特定文件来解决这一问题-CRC将更改,但总体文件大小不会更改(只要您保持在单个文件的边界内)。在

但您至少需要:

  1. 更新文件CRC
  2. 更新中心目录的CRC

值得注意的是,位于文件末尾的中心目录是一个很好的特性,因为它意味着您可以动态地生成“动态”的zip文件。不久前,我为一家在线销售MP3的公司做了一个“动态”的zip打包机,它将MP3文件与正确的zip头连接在一起,这样你就可以将一堆歌曲添加到“下载列表”中,这将把mp3从他们家的磁盘直接流到客户端-注入正确的头信息,最后是中央目录记录-从web服务器端它只是一系列的读写操作,但在客户端它看起来像一个真正的zip文件。在

相关问题 更多 >