Catherine Catherine - 7 months ago 11
Python Question

Python: Create a zip file of all files ending with ".json" in a directory

Let's say the directory is /Home/Documents/Test_files.

I would like to create a zip file of all the files ending with ".json" and if possible delete the files so that only the zip file is left

So far I have been able to create a zip file of all the files in the given path but when I use the line

zipf.write(file)
it throws the error "[Errno 2] No such file or directory: sample.json". However when I use
zipf.write(os.path.join(root, file))
it does write the files but also the whole directory path which I don't want.

I just want to write the files themselves. When I use
print file
the correct files seemed to be printed so I don't know why I get the error that the file doesn't exist

Currently my code looks like this:

def create_zip(path,zipf):
#path is the directory address (i.e. /Home/Documents/Test_files)
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".json"):
print file
zipf.write(os.path.join(root, file))
#zipf.write(file)


I would also like to remove/delete the files after creating the zip file to save space.

Any help as to why this is happening would be appreciated!

Answer

You can chdir before adding it to zip file not to include the whole directory path and use os.remove to delete the files afterwards:

def create_zip(path,zipf):
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.endswith(".json"):
                chdir(root)
                zipf.write(file)
                os.remove(file)