我需要从 zip 文件中名为 QuickLooks 的文件夹中提取一个名为 Preview.pdf 的文件。
现在我的代码看起来有点像这样:
with ZipFile(newName, 'r') as newName:
newName.extract(\QuickLooks\Preview.pdf)
newName.close()
(在这种情况下,newName
已设置为等于 zip 的完整路径)。
重要的是要注意反斜杠在这种情况下是正确的,因为我在 Windows 上。
代码不起作用;这是它给出的错误:
Traceback (most recent call last):
File "C:\Users\Asit\Documents\Evam\Python_Scripts\pageszip.py", line 18, in <module>
ZF.extract("""QuickLooks\Preview.pdf""")
File "C:\Python33\lib\zipfile.py", line 1019, in extract
member = self.getinfo(member)
File "C:\Python33\lib\zipfile.py", line 905, in getinfo
'There is no item named %r in the archive' % name)
KeyError: "There is no item named 'QuickLook/Preview.pdf' in the archive"
我正在从 Notepad++ 内部运行 Python 脚本,并从其控制台获取输出。
我怎样才能做到这一点?
或者,我如何提取整个 QuickLooks 文件夹,移出 Preview.pdf,然后删除该文件夹及其其余内容?
只是为了上下文,这是脚本的其余部分。这是一个获取 .pages 文件的 PDF 的脚本。我知道那里有 Bonified 转换器。我只是将其作为某种实际应用程序的练习。
import os.path
import zipfile
from zipfile import *
import sys
file = raw_input('Enter the full path to the .pages file in question. Please note that file and directory names cannot contain any spaces.')
dir = os.path.abspath(os.path.join(file, os.pardir))
fileName, fileExtension = os.path.splitext(file)
if fileExtension == ".pages":
os.chdir(dir)
print (dir)
fileExtension = ".zip"
os.rename (file, fileName + ".zip")
newName = fileName + ".zip" #for debugging purposes
print (newName) #for debugging purposes
with ZipFile(newName, 'w') as ZF:
print("I'm about to list names!")
print(ZF.namelist()) #for debugging purposes
ZF.extract("QuickLook/Preview.pdf")
os.rename('Preview.pdf', fileName + '.pdf')
finalPDF = fileName + ".pdf"
print ("Check out the PDF! It's located at" + dir + finalPDF + ".")
else:
print ("Sorry, this is not a valid .pages file.")
sys.exit
我不确定导入是否Zipfile
是多余的;我在另一篇 SO 帖子上读到它from zipfile import *
比import zipfile
. 我不确定,所以我两个都用了。=)
编辑:我已更改代码以反映 Blckknght 建议的更改。