使用Python压缩文件

时间:2015-12-22 06:53:28

标签: python python-2.7 zipfile

Python新手,但对编程很老。我来到这里是因为无论何时我搜索Python参考,我最好的答案都在这里。当谈到当前的问题时,请相信我,我已经广泛地看过这里,当我得到我想要的答案时,他们并不总是有效。

所以这是我的问题。很简单,我只想用Python来压缩文件,并验证所说的zip文件。

以下是相关代码:

import zipfile

archive_file_list = ['archive1','archive2']

LogIt(log_file,"checking for existance of archive directory")
if os.path.isdir(archive_path) == True:
    LogIt(log_file,'archive directory found')
    LogIt(log_file,'looking for files to archive')
    for a in archive_file_list:
        target_file = archive_path + a + '.txt'
        LogIt(log_file,'looking for file : ' + target_file)
        if os.path.isfile(target_file) == True:
            LogIt(log_file,'file found')
            zip_file = archive_path + a + '.zip'
            LogIt(log_file,'creating zip file : ' + zip_file)
            zf = zipfile.ZipFile(zip_file,'w')
            zf.write(target_file,zip_file,compress_type=zipfile.ZIP_DEFLATED)
            zf.close
            LogIt(log_file,'Zip file created')
            LogIt(log_file,'verifying')
            if os.path.isfile(zip_file) == True:
                LogIt(log_file,'zip file exists')
                LogIt(log_file,'verifying zip file')
                if zipfile.is_zipfile(zip_file) == True:
                    LogIt(log_file,'file ' + zip_file + ' verified')
                else:
                    LogIt(log_file,'file ' + zip_file + ' not verified')
                # print_info(zip_file)
            else:
                LogIt(log_file,'unable to verify zip file')
        else:
            LogIt(log_file,'file not found')
else:
    LogIt(log_file,'archive path not found, no files to zip')

在大多数情况下它工作正常,指定的文件是压缩的。我可以通过pkzip或Rar在我移动它的任何机器上阅读它。但是当我真正检查这是否是一个有效的zip文件时,我会被关闭,用一个体面的编辑器查看文件显示它确实以“PK”或“Pk”开头,我忘记了,但它肯定会出现是有效的。

if zipfile.is_zipfile(zip_file) == True:

这总是返回False,我只是不明白。

预先感谢您的协助。 吉姆

1 个答案:

答案 0 :(得分:1)

这一行是你的问题:

zf.close

你实际上并没有打电话,因为你省略了parens。所以你只是声明没有任何效果。在python程序退出后文件将关闭,因此您在该点有一个有效的zip文件,但在您进行检查时却没有。将其更改为zf.close(),我打赌你看到你的zipfile验证。