访问zipfi中文件夹中的文件

2024-03-29 13:42:50 发布

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

我想访问zip文件中的文件(xml文件),以便对它们进行过滤。但是我怎样才能深入到zip文件中的文件夹来访问文件呢?我的问题是我不能通过zip访问文件_文件名列表如果它们在某些文件夹中,下面是我的代码:

import sys, getopt
from lxml import etree
from io import StringIO
import zipfile

def main(argv):

    inputfile = ''
    outputfile = ''
    try:
       opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
    except getopt.GetoptError:
       print 'test.py -i <inputfile> -o <outputfile>'
       sys.exit(2)
    for opt, arg in opts:
       if opt == '-h':
          print 'test.py -i <inputfile> -o <outputfile>'
          sys.exit()
       elif opt in ("-i", "--ifile"):
          inputfile = arg
       elif opt in ("-o", "--ofile"):
          outputfile = arg

    archive = zipfile.ZipFile(inputfile, 'r')

    with archive as zip_file:
      for file in zip_file.namelist():
          if file.endswith(".amd"):
              try:

                  print("Process the file")
                  xslt_root = etree.XML('''\
                    <xsl:stylesheet version="1.0"
                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

                    <xsl:template match="node() | @*">
                      <xsl:copy>
                          <xsl:apply-templates select="node() | @*"/>
                      </xsl:copy>
                    </xsl:template>


                    <xsl:template match="TimeStamp"/>
                    <xsl:template match="@timeStamp"/>
                    <xsl:template match="TimeStamps"/>
                    <xsl:template match="Signature"/>

                    </xsl:stylesheet>
                    ''')

                  transform = etree.XSLT(xslt_root)

                  doc = etree.parse(zip_file.open(file))
                  result_tree = transform(doc)

                  resultfile = unicode(str(result_tree))
                  zip_file.write(resultfile)


              finally:
                  zip_file.close()

if __name__=='__main__':
     main(sys.argv[1:])

例外:它不能读取“ex4逯linktime/”,因为这是一个文件夹而不是一个文件!在

^{pr2}$

异常2:不回写已更改的文件!在

 File "C:\Python27\lib\zipfile.py", line 1033, in write
    st = os.stat(filename)
WindowsErrorProcess the file
: [Error 3] The system cannot find the path specified: u'<?xml version="1.0"?   >\n<ComponentData toolVersion="V6.1.4" schemaVersion="6.1.0.0">\n\t<dataset name="Bank1">...

Tags: 文件inimport文件夹matchsystemplatezip
1条回答
网友
1楼 · 发布于 2024-03-29 13:42:50
  • 当您执行etree.parse(file)操作时,文件只是一个字符串。etree不知道它必须在zip文件中搜索该名称,它只会在当前目录中查找。尝试:

    doc = etree.parse(zip_file.open(file))
    
  • 您还必须跳过目录名,这些名称后面有一个斜杠:

    for filename in zip_file.namelist():
        if filename.endswith('/'):
            # skip directory names
            continue
    
  • 要更新zip文件,请使用:

    zip_file.writestr(filename, resultfile)
    

相关问题 更多 >