【问题标题】:Extract content from a file with mime multipart使用 mime multipart 从文件中提取内容
【发布时间】:2011-04-23 03:15:15
【问题描述】:

我有一个包含 tiff 图像和多部分 mime 文档中的文档 xml 的文件。 我会从这个文件中提取图像。 我怎样才能得到它?

我有这段代码,但如果我有一个大文件(例如 30Mb),它需要无限的时间来提取它,所以这没有用。

f=open("content_file.txt","rb")
msg = email.message_from_file(f)
j=0
image=False
for i in msg.walk():
    if i.is_multipart():
        #print "MULTIPART: "
        continue
    if i.get_content_maintype() == 'text':
        j=j+1
        continue
    if i.get_content_maintype() == 'image':
        image=True
        j=j+1
        pl = i.get_payload(decode=True)
        localFile = open("map.out.tiff", 'wb')
        localFile.write(pl)
        continue
        f.close()
    if (image==False):
        sys.exit(0);

非常感谢。

【问题讨论】:

    标签: python mime mime-types


    【解决方案1】:

    已解决:

    def extract_mime_part_matching(stream, mimetype):
    """Return the first element in a multipart MIME message on stream
    matching mimetype."""
    
    msg = mimetools.Message(stream)
    msgtype = msg.gettype()
    params = msg.getplist()
    
    data = StringIO.StringIO()
    if msgtype[:10] == "multipart/":
    
        file = multifile.MultiFile(stream)
        file.push(msg.getparam("boundary"))
        while file.next():
            submsg = mimetools.Message(file)
            try:
                data = StringIO.StringIO()
                mimetools.decode(file, data, submsg.getencoding())
            except ValueError:
                continue
            if submsg.gettype() == mimetype:
                break
        file.pop()
    return data.getvalue()
    

    来自: http://docs.python.org/release/2.6.6/library/multifile.html

    感谢您的支持。

    【讨论】:

      【解决方案2】:

      我不太清楚为什么您的代码会挂起。缩进看起来有点错误,打开的文件没有正确关闭。您也可能内存不足。

      这个版本适合我:

      import email
      import mimetypes
      
      with open('email.txt') as fp:
          message = email.message_from_file(fp)
      
      for i, part in enumerate(message.walk()):
          if part.get_content_maintype() == 'image':
              filename = part.get_filename()
              if not filename:
                  ext = mimetypes.guess_extension(part.get_content_type())
                  filename = 'image-%02d%s' % (i, ext or '.tiff')
              with open(filename, 'wb') as fp:
                  fp.write(part.get_payload(decode=True))
      

      (部分取自http://docs.python.org/library/email-examples.html#email-examples

      【讨论】:

      • 它适用于小文件...但我必须管理大文件(例如 30mb),它不能很好地工作。需要很长时间,而且cpu总是被加载。
      猜你喜欢
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 2012-09-04
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      相关资源
      最近更新 更多