Python 如何提取zip中文件夹中的文件?
我需要从zip文件中名为QuickLooks的文件夹中提取一个名为Preview.pdf的文件 现在我的代码看起来有点像这样:Python 如何提取zip中文件夹中的文件?,python,file-extension,zipfile,sys,os.path,Python,File Extension,Zipfile,Sys,Os.path,我需要从zip文件中名为QuickLooks的文件夹中提取一个名为Preview.pdf的文件 现在我的代码看起来有点像这样: with ZipFile(newName, 'r') as newName: newName.extract(\QuickLooks\Preview.pdf) newName.close() (在本例中,newName已设置为与zip的完整路径相等) 需要注意的是,在这种情况下,反斜杠是正确的,因为我使用的是Windows 代码不起作用
with ZipFile(newName, 'r') as newName:
newName.extract(\QuickLooks\Preview.pdf)
newName.close()
(在本例中,newName
已设置为与zip的完整路径相等)
需要注意的是,在这种情况下,反斜杠是正确的,因为我使用的是Windows
代码不起作用;下面是它给出的错误:
回溯(最近一次呼叫最后一次):
文件“C:\Users\Asit\Documents\Evam\Python\u Scripts\pageszip.py”,第18行,在
ZF.extract(“'QuickLooks\Preview.pdf”“”)
文件“C:\Python33\lib\zipfile.py”,第1019行,摘录
member=self.getinfo(成员)
getinfo中第905行的文件“C:\Python33\lib\zipfile.py”
'存档“%name”中没有名为%r的项)
KeyError:“存档中没有名为'QuickLook/Preview.pdf'的项目”
我正在从Notepad++内部运行Python脚本,并从其控制台获取输出
我怎样才能做到这一点
或者,如何提取整个QuickLooks文件夹,移出Preview.pdf,然后删除该文件夹及其其余内容
下面是脚本的其余部分,仅供参考。这是一个获取.pages文件PDF的脚本。我知道那里有骨化的转换器;我只是在做一些实际应用的练习
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帖子上读到,使用zipfile导入*的比使用导入zipfile
更好。我不确定,所以我两个都用了
编辑:我修改了代码,以反映Blckknght建议的更改。以下是一些似乎有效的方法。您的代码有几个问题。正如我在评论中提到的,zipfile必须以“r”模式打开才能读取。另一个原因是,zip存档成员名称在其路径名中始终使用正斜杠/
字符作为分隔符(请参阅本手册第4.4.17.1节)。需要注意的是,使用Python当前的zipfile
模块无法将嵌套的存档成员提取到不同的子目录。您可以控制根目录,但不能控制根目录下的任何内容(即zip中的任何子文件夹)
最后,由于没有必要将.pages文件重命名为.zip—您传递的文件名ZipFile()
可以有任何扩展名—我从代码中删除了所有扩展名。但是,为了克服将成员提取到不同子目录的限制,我必须添加代码,首先将目标成员提取到临时目录,然后将其复制到最终目标。当然,之后需要删除此临时文件夹。所以我不确定最终结果会简单得多
import os.path
import shutil
import sys
import tempfile
from zipfile import ZipFile
PREVIEW_PATH = 'QuickLooks/Preview.pdf' # archive member path
pages_file = input('Enter the path to the .pages file in question: ')
#pages_file = r'C:\Stack Overflow\extract_test.pages' # hardcode for testing
pages_file = os.path.abspath(pages_file)
filename, file_extension = os.path.splitext(pages_file)
if file_extension == ".pages":
tempdir = tempfile.gettempdir()
temp_filename = os.path.join(tempdir, PREVIEW_PATH)
with ZipFile(pages_file, 'r') as zipfile:
zipfile.extract(PREVIEW_PATH, tempdir)
if not os.path.isfile(temp_filename): # extract failure?
sys.exit('unable to extract {} from {}'.format(PREVIEW_PATH, pages_file))
final_PDF = filename + '.pdf'
shutil.copy2(temp_filename, final_PDF) # copy and rename extracted file
# delete the temporary subdirectory created (along with pdf file in it)
shutil.rmtree(os.path.join(tempdir, os.path.split(PREVIEW_PATH)[0]))
print('Check out the PDF! It\'s located at "{}".'.format(final_PDF))
#view_file(final_PDF) # see Bonus below
else:
sys.exit('Sorry, that isn\'t a .pages file.')
奖励:如果您想实际查看脚本中的最终pdf文件,可以添加以下功能并在创建的最终pdf上使用它(假设您的系统上安装了pdf viewer应用程序):
您正在使用ZipFile(newName,'w')
打开文件进行写入,但未读取。@martineau谢谢!我修复了它。@martineau值得添加它作为一个答案,这样就可以用一个解决方案检查它。@legostrmtroopr我还没有用脚本尝试过它…我会尝试一下,让你知道。它没有修复问题…行shutil.rmtree(os.path.join(tempdir,os.path.split(PREVIEW\u path)[0])
和print是什么('Check the PDF!它位于“{}.”格式(final_PDF))
do?thermtree()
call删除通过提取preview.pdf文件创建的临时子目录。它通过使用拆分preview\u PATH
的第一部分来获取目录名,这将导致QuickLooks
,然后将临时目录路径连接到该路径以获得指向它的完整路径。format()
是一种字符串方法,它将其字符串用作格式规范或模式。这两种功能都在联机文档中介绍。
import subprocess
def view_file(filepath):
subprocess.Popen(filepath, shell=True).wait()