[英]Zipping a binary file in python
我試圖在zip文件中包含一個二進制文件,下面是代碼片段:我首先將zip內容解壓縮到一個臨時位置,然后添加更多文件並將其壓縮回新的存檔。
import zipfile
def test(fileName, tempDir):
# unzip the file contents,may contain binary files
myZipFile=zipfile.ZipFile(fileName,'r')
for name in myZipFile.namelist():
toFile = tempDir + '/' + name
fd = open(toFile, "w")
fd.write(myZipFile.read(name))
fd.close()
myZipFile.close()
# code which post processes few of the files goes here
#zip it back
newZip = zipfile.ZipFile(fileName, mode='w')
try:
fileList = os.listdir(tempDir)
for name in fileList:
name = tempDir + '/' + name
newZip.write(name,os.path.basename(name))
newZip.close()
except Exception:
print 'Exception occured while writing to PAR file: ' + fileName
一些文件可能是二進制文件。 壓縮代碼工作正常但是當我嘗試使用linux的unzip或python的zip模塊解壓縮時,我得到以下錯誤:
zipfile損壞。 (請檢查您是否已在相應的BINARY模式下轉移或創建了zipfile,並且您已正確編譯UnZip)
我正在使用python 2.3
這里出了什么問題?
你可能想要升級,因為Python 2.3真的已經過時了。 2.7.3是最新的2.x版本和3.2.3最新的python版本。
請參閱docs.python.org :
| extractall(self, path=None, members=None, pwd=None)
| Extract all members from the archive to the current working
| directory. `path' specifies a different directory to extract to.
| `members' is optional and must be a subset of the list returned
| by namelist().
(2.6版新增功能)
看看Zip文件夾及其內容 。
您可能也對distutlis.archive_util感興趣。
嗯不確定它是否是python 2.3中的一個bug。 目前的工作環境不允許我升級到python的更高版本:-( :-( :-(
以下解決方法有效:
import zipfile
def test(fileName, tempDir):
# unzip the file contents,may contain binary files
myZipFile=zipfile.ZipFile(fileName,'r')
for name in myZipFile.namelist():
toFile = tempDir + '/' + name
# check if the file is a binary file
#if binary file, open it in "wb" mode
fd = open(toFile, "wb")
#else open in just "w" mode
fd = open(toFile, "w")
fd.write(myZipFile.read(name))
fd.close()
myZipFile.close()
# code which post processes few of the files goes here
#zip it back
newZip = zipfile.ZipFile(fileName, mode='w')
try:
fileList = os.listdir(tempDir)
for name in fileList:
name = tempDir + '/' + name
newZip.write(name,os.path.basename(name))
newZip.close()
except Exception:
print 'Exception occured while writing to PAR file: ' + fileName
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.