nested directory appear while creating zip file
<p>I am quite new to python.Here i am trying to create zip file of "diveintomark-diveintopython3-793871b' directory.I changed the current working directory using os.chdir() function.The zip file is created but the problem is when i extract the zip file i get the the following directory</p>

<pre><code>Users/laiba/Desktop/diveintomark-diveintopython3-793871b 
</code></pre>

<p>but i only want <strong>diveintomark-diveintopython3-793871b</strong> folder inside my zip folder not the whole nested directory created .Why is this happening and how i can solve this?</p>

<pre><code>import zipfile, os

os.chdir('c:\\Users\\laiba\\Desktop')
myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
    myzip.write(folder)
    for each in subfolder:
        myzip.write(os.path.abspath(os.path.join(folder,each)))
    for each in file:
        myzip.write(os.path.abspath(os.path.join(folder,each)))
</code></pre>

<p>you could use argument <code>arcname</code>: name of the item in the archive as opposed to the full path name. But here you don't need it because you already are in the correct directory. Just drop the <code>abspath</code> and you're done (and also the duplicate folder entry)</p>

<pre><code>import zipfile, os

os.chdir('c:\\Users\\laiba\\Desktop')

myzip=zipfile.ZipFile('diveZip.zip','w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk('diveintomark-diveintopython3-793871b'):
    for each in subfolder+file:
        myzip.write(os.path.join(folder,each))
myzip.close()
</code></pre>

<p>This is possible to do without changing directories but more complex, also more elegant since you don't have to chdir</p>

<pre><code>import zipfile, os

root_dir = r"c:\Users\laiba\Desktop"
myzip=zipfile.ZipFile(os.path.join(root_dir,'diveZip.zip'),'w',zipfile.ZIP_DEFLATED)

for folder,subfolder,file in os.walk(os.path.join(root_dir,'diveintomark-diveintopython3-793871b')):
    for each in subfolder+file:
        source = os.path.join(folder,each)
        # remove the absolute path to compose arcname
        # also handles the remaining leading path separator with lstrip
        arcname = source[len(root_dir):].lstrip(os.sep)
        # write the file under a different name in the archive
        myzip.write(source,arcname=arcname)

myzip.close()
</code></pre>

python zipfile