Apr 7

Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too.

Changed in version 3.1: Support for file and file-like objects.


python版本 3.3.5

Python 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:37:12) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.


def unpack():
    BASE_DIR = os.path.abspath(".")
    TAR_DIR = os.path.join(BASE_DIR, 'tar')
    tars = map(lambda x: os.path.join(TAR_DIR, x), os.listdir(TAR_DIR))
    for x in tars:
        if tarfile.is_tarfile(x):
            #myfile = tarfile.TarFile(x, 'r')
            #tarfile.TarFile.extractall(myfile, TAR_DIR)
        elif zipfile.is_zipfile(x):
            myfile = zipfile.ZipFile(x, 'r')
            f = myfile.namelist()[0]
            p = os.path.join(TAR_DIR, f)
            if not os.path.exists(p):
                zipfile.ZipFile.extractall(myfile, TAR_DIR)

bug出现的情况: 在测试flup-py3.3-master.zip是否为zifile时, 即zipfile.is_zipfile(x), 出现以下错误

Traceback (most recent call last):
  File "install.py", line 48, in <module>
  File "install.py", line 36, in unpack_install
    if tarfile.is_tarfile(x):
  File "C:\Python33\lib\tarfile.py", line 2444, in is_tarfile
    t = open(name)
  File "C:\Python33\lib\tarfile.py", line 1573, in open
    return func(name, "r", fileobj, **kwargs)
  File "C:\Python33\lib\tarfile.py", line 1638, in gzopen
    fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj)
  File "C:\Python33\lib\gzip.py", line 184, in __init__
    fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
PermissionError: [Errno 13] Permission denied: 'F:\\dep\\tar\\flup-py3.3-master'
shell returned 1


[待证]更进一步,应该是测试时,使用了当前目录作为试解压的目录. 因为已经有flup-py3.3-master这个目录了.所以错误就出现了.

附下载地址 flup-py3.3-master.zip