使用Python在文件名中提取带有无效字符的文件 [英] Extract files with invalid characters in filename with Python
问题描述
我使用python的zipfile模块来提取.zip存档(让我们将这个文件放在 http ://img.dafont.com/dl/?f = akvaleir 例如。)
I use python's zipfile module to extract a .zip archive (Let's take this file at http://img.dafont.com/dl/?f=akvaleir for example.)
f = zipfile.ZipFile('akvaleir.zip', 'r')
for fileinfo in f.infolist():
print fileinfo.filename
f.extract(fileinfo, '.')
其输出:
Akval�ir_Normal_v2007.ttf
Akval�ir, La police - The Font - Fr - En.pdf
这两个文件在提取后都无法访问,因为它们的文件名中有无效的编码字符。问题是zipfile模块没有指定输出文件名的选项。
Both files are unaccessable after extraction because there are invalid encoded characters in their filenames. The problem is zipfile module doesn't have an option to specify output filenames.
但是,unzip akvaleir.zip转义文件名:
However, "unzip akvaleir.zip" escapes the filename well:
root@host:~# unzip akvaleir.zip
Archive: akvaleir.zip
inflating: AkvalВir_Normal_v2007.ttf
inflating: AkvalВir, La police - The Font - Fr - En.pdf
我尝试捕获 unzip -l akvaleir.zip在我的python程序中,这两个文件名是:
I tried capturing output of "unzip -l akvaleir.zip" in my python program and these two filenames are:
Akval\xd0\x92ir_Normal_v2007.ttf
Akval\xd0\x92ir, La police - The Font - Fr - En.pdf
如何获取正确的文件名,如unzip命令所在,而不捕获unzip -l akvaleir.zip的输出?
How can I get the correct filename like what unzip command does without capturing output of "unzip -l akvaleir.zip"?
推荐答案
p>而不是 extract
方法,请使用 打开
方法,并将生成的伪文件以任何您想要的名称保存到磁盘,例如使用 shutil.copyfileobj
。
Instead of the extract
method, use the open
method and save the resulting pseudofile to disk under whatever name you wish, for example with shutil.copyfileobj
.
这篇关于使用Python在文件名中提取带有无效字符的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!