質問

I have a short method that takes a file path and list of filenames from that path as parameters and is supposed to zip all those files into one archive file. The problem is that instead of zipping up the files, it just creates an empty directory in the archive for each file I am trying to zip. Here's the method:

 def zip(self, file_path, filename_list):

        f = zipfile.ZipFile(file_path + '_converted_zip_archive.zip', 'w')
        for filename in filename_list:
            f.write(file_path, filename)

        f.close()

If I call

zip('uploads/', ['test_1.txt', 'test_2.txt', 'test_3.txt'])

I end up with an archive file that has the following directories:

/test_1.txt/
/test_2.txt/
/test_3.txt/

What am I doing wrong that I'm creating a bunch of empty directories in the ZIP file instead of actually zipping up these text files?

役に立ちましたか?

解決

You are writing your directory to the archive three times (with three different names). To be more explicit, you are writing the following to the archive:

uploads/ as test_1.txt
uploads/ as test_2.txt
uploads/ as test_3.txt

Do you rather mean to do this?

def zip(self, file_path, filename_list):
    f = zipfile.ZipFile(file_path + '_converted_zip_archive.zip', 'w')
    for filename in filename_list:
        f.write(file_path + filename, filename)  # note the addition of filename here
    f.close()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top