2012-01-27 29 views
3

使用zipfile模塊我創建了一個腳本來提取我的歸檔文件,但該方法正在破壞除txt文件以外的所有內容。如何在Windows上使用Python調用WinRar?仍然存在問題

def unzip(zip): 
     filelist = [] 
     dumpfold = r'M:\SVN_EReportingZones\eReportingZones\data\input\26012012' 
     storage = r'M:\SVN_EReportingZones\eReportingZones\data\input\26012012__download_dump' 
     file = storage + '\\' + zip 
     unpack = dumpfold + '\\' + str(zip) 
     print file 

     try: 

        time.sleep(1) 
        country = str(zip[:2]) 
        countrydir = dumpfold + '\\' + country 
        folderthere = 0 
        if exists(countrydir): 
         folderthere = 1   

        if folderthere == 0: 
         os.makedirs(countrydir) 

        zfile = zipfile.ZipFile(file, 'r') 
##      print zf.namelist() 
        time.sleep(1) 
        shapepresent = 0 

在這裏,我有一個問題 - 通過讀取和寫入的數據壓縮,zip文件命令似乎使其不可通過相關的方案 - 我想解壓縮shape文件在ArcGIS中使用...

     for info in zfile.infolist(): 
         fname = info.filename 
         data = zfile.read(fname) 
         zfilename = countrydir + '\\' + fname 
         fout = open(zfilename, 'w')# reads and copies the data 
         fout.write(data) 
         fout.close() 
         print 'New file created ----> %s' % zfilename 





     except: 
         traceback.print_exc() 
         time.sleep(5) 

是否有可能使用系統命令調用WinRar,並讓它爲我解開包裝?歡呼聲中,亞歷克斯

編輯

曾使用WB法,它適用於大多數的我的文件,但有些仍然被破壞。當我使用winRar手動解壓縮有問題的文件時,它們會正確加載,並且它們還顯示更大的文件大小。

請有人指點我加載winRar的方向來完成解壓縮過程嗎?

回答

0

要回答你的問題的第二部分,我建議envoy library。與特使使用WinRAR:

import envoy 
r = envoy.run('unrar e {0}'.format(zfilename)) 
if r.status_code > 0: 
    print r.std_err 
print r.std_out 

要做到這一點,而不使者:

import subprocess 
r = subprocess.call('unrar e {0}'.format(zfilename), shell=True) 
print "Return code for {0}: {1}".format(zfilename, r) 
+0

感謝您的回答。不幸的是,安裝envoy代碼吐出這個錯誤:Traceback(最近調用最後一個): 文件「C:\ Python26 \ ArcGIS10.0 \ lib \ threading.py」,第532行,在__bootstrap_inner中 self.run() 文件「C:\ Python26 \ ArcGIS10.0 \ lib \ threading.py」,行484,在運行 self .__ target(* self .__ args,** self .__ kwargs) File「build \ bdist.win32 \ egg \文件「C:\ Python26 \ ArcGIS10.0 \ lib \ subprocess.py」,第633行,在__init__中 errread,errwrite) 文件「C:envoy \ core.py」,第40行,目標爲 bufsize = 0, 文件「C :\ Python26 \ ArcGIS10.0 \ lib \ subprocess.py「,行842,在_execute_child中...... – 2012-02-02 14:46:22

+0

更具體的文件」M:\ SVN_EReportingZones \ eReportingZones \ data \ scripts \ file_unzipper_alpha999.py「,行101,解壓縮後 r = envoy.run('unrar e {0}'.format(unpack)) 運行中的文件「build \ bdist.win32 \ egg \ envoy \ core.py」,第167行,運行 out,err = cmd。運行(數據,超時) 文件「build \ bdist.win32 \ egg \ envoy \ core.py」,行52,運行 self.returncode = self.process.returncode AttributeError:'NoneType'對象沒有屬性' returncode' – 2012-02-02 14:50:41

+0

@AlexOulton我只用了python27的envoy。我的猜測是特使試圖使用僅添加了2.7的功能,因此請嘗試僅用於子流程的版本。 – 2012-02-02 15:13:39

3

您正在打開文件文本模式。嘗試:

 fout = open(zfilename, 'wb')# reads and copies the data 

b打開文件的二進制模式,在運行時庫不要試圖做任何換行轉換。

+0

三江源!它現在完美運行! – 2012-01-27 10:27:42

相關問題