开发者

Python Zip-File, wildcards

I was wondering how I could tell Python to extract only ".txt" files from a zip folder, 开发者_如何学Gousing a wildcard. This code works fine for me:

extractor.extract("\websitefiles\test.hmtl")"

How can I use this same code to extract all .txt files in that current directory? I was thinking something like this:

extractor.extract(".*.txt")

but it failed to work.. Any ideas???


First, you need the file names list, using namelist(). Then, you can filter the "*.txt" files with txtfiles = fnmatch.filter(fn_list,"*.txt") Now you can extract the files one by one:

extracts = [ extractor.extract(txt) for txt in txtfiles ]


I just need python to extract .txt files in the current directory, that are no larger than 3 megabytes.

#!/usr/bin/env python
import zipfile
from contextlib import closing

MiB = 2**20 # mebibyte

with closing(zipfile.ZipFile("example.zip")) as zfile:
    for info in zfile.infolist():
        if info.filename.endswith('.txt') and 0 < info.file_size <= 3*MiB:
            zfile.extract(info)


You would need to get the listing of all the files in the ZIP, then ask for each one, one at a time. Zipfile has the namelist() method to give you that list.


Use the function namelist() to get the names of the files. Then select the txt files from the list and extract them one by one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜