1

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!

0

2 Answers 2

2

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)
0
1

If you're using Python's ZipFile module, you can just specify the argument

arcname = archive name

in the write() method, as in:

    import os
    from zipfile import ZipFile

    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), arcname=file)
                    os.remove(os.path.join(root, file))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.