使用 Python zipfile 从 ZIP 中提取包含文件名特定字符串的文件
Extract file that contains specific string on filename from ZIP using Python zipfile
我有一个 ZIP 文件,我需要提取文件名中包含字符串 "test" 的所有文件(通常是一个)。都是xlsx文件。
我正在为此使用 Python 压缩文件。这是我的无效代码:
zip.extract(r'*\test.*\.xlsx$', './')
我得到的错误:
KeyError: "There is no item named '*\\test.*\\.xlsx$' in the archive"
有什么想法吗?
你这里有多个问题:
r
只是将字符串视为原始字符串,看起来您可能认为它创建了一个正则表达式对象; (无论如何,zip.extract()
只接受字符串)
- 正则表达式开头的
*
量词前面没有要匹配的字符
您需要手动遍历 zip 文件索引并将文件名与您的正则表达式进行匹配:
from zipfile import ZipFile
import re
zip = ZipFile('myzipfile.zip')
for info in zip.infolist():
if re.match(r'.*test.*\.xlsx$', info.filename):
print info.filename
zip.extract(info)
您也可以考虑使用 shell 文件 globbing 语法:fnmatchcase(info.filename, '*.test.*.xls')
(在幕后它会将其转换为正则表达式,但它会使您的代码稍微简单一些)
我有一个 ZIP 文件,我需要提取文件名中包含字符串 "test" 的所有文件(通常是一个)。都是xlsx文件。
我正在为此使用 Python 压缩文件。这是我的无效代码:
zip.extract(r'*\test.*\.xlsx$', './')
我得到的错误:
KeyError: "There is no item named '*\\test.*\\.xlsx$' in the archive"
有什么想法吗?
你这里有多个问题:
r
只是将字符串视为原始字符串,看起来您可能认为它创建了一个正则表达式对象; (无论如何,zip.extract()
只接受字符串)- 正则表达式开头的
*
量词前面没有要匹配的字符
您需要手动遍历 zip 文件索引并将文件名与您的正则表达式进行匹配:
from zipfile import ZipFile
import re
zip = ZipFile('myzipfile.zip')
for info in zip.infolist():
if re.match(r'.*test.*\.xlsx$', info.filename):
print info.filename
zip.extract(info)
您也可以考虑使用 shell 文件 globbing 语法:fnmatchcase(info.filename, '*.test.*.xls')
(在幕后它会将其转换为正则表达式,但它会使您的代码稍微简单一些)