I want to zip just a file in Python which present in a folder. I am finding hard to create zip file with the below code snippet. It does create zip file, but it has complete folder structure inside.
import zipfile as zip
root=r"C:\XXXX\YYYYYY\ZZZZ\"
file="abc.txt"
zipper=zip.ZipFile(file=os.path.join(root,file.replace("txt","zip")),mode="w",compression=zip.ZIP_DEFLATED)
zipper.write(os.path.join(root,file))
zipper.close()
Actual output:
#################
abc.zip
|
XXXX - Folder
|
YYYYYY - Folder
|
ZZZZ - Folder
|
abc.txt
Expected output
###############
abc.zip
|
abc.txt
One way I learnt and working is :
os.chdir(root)
To set the working directory to the folder where the files are present. Then, pass just the filename instead of complete path to create zip.
Not sure, if it is the correct and best way.
zipfile : zip only the files present in a directory