如何在Windows上用Python调用WinRar?仍然存在问题

3 投票
2 回答
5715 浏览
提问于 2025-04-17 11:12

我使用zipfile模块写了一个脚本来解压我的压缩文件,但这个方法除了txt文件以外,其他文件都坏掉了。

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

我遇到一个问题——在读取和写入压缩数据时,zipfile命令似乎让这些文件无法被相关程序使用——我想解压shapefile文件,以便在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,让它帮我解压?谢谢,Alex

编辑

我使用了wb方法,大部分文件都能正常工作,但有些文件还是坏掉了。当我用WinRar手动解压那些有问题的文件时,它们能正常加载,而且文件大小也更大。

请问有没有人能告诉我怎么用WinRar完成整个解压过程?

2 个回答

0

针对你问题的第二部分,我建议你使用envoy库。如果你想用winRar配合envoy,可以这样做:

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

如果不使用envoy的话,可以这样做:

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

你现在是以文本模式打开文件的。试试这个:

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

这里的b表示以二进制模式打开文件,这样运行时的库就不会尝试进行换行符的转换。

撰写回答