2010-10-08 56 views
2

我有一個文件,其中包含多部分MIME文檔中的tiff圖像和文檔xml。 我會從這個文件中提取圖像。 我怎麼能得到它?從MIME多部分文件中提取內容

我有這個代碼,但它需要無限的時間來提取它,如果我有一個大文件(例如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); 

非常感謝。

回答

4

解決:

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

感謝您的支持。

0

這不是很清楚,爲什麼你的代碼掛起。縮進看起來有點不對,打開的文件沒有正確關閉。你的內存也可能很低。

這個版本對我來說工作得很好:

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拍攝)

+0

它適用於小文件......但我必須管理大文件(例如30mb),並且效果不佳。這需要很長時間,並且CPU總是被加載。 – michele 2010-10-09 08:48:01

+0

有什麼建議?謝謝。 – michele 2010-10-09 08:48:29