'Getting blank content from namelist()

I am trying to write a script that will allow me to search for the most recently downloaded file (which will be a docx), zip that file, and then search for specific parts of the document in XML. I am stuck at this part where I am trying to zip the file. When I run namelist(), I am getting blank content and not the content of my intended file.

import glob 
import os

list_of_files = glob.iglob('C:\\Users\\username\\Downloads\\*') 
latest_file = max(list_of_files, key=os.path.getctime)

import re
import zipfile
import xml.dom.minidom

os.chdir('C:\\Users\\username\\Downloads\\')

zf = zipfile.ZipFile('latest_file','w')

print(zf.namelist())


Solution 1:[1]

It looks like your issue is that you are opening your zipfile in write mode with this:

zf = zipfile.ZipFile('latest_file','w')

Doing so you automaticaly overwrite your existing file with a blank zip file, hence the empty zf.namelist(). Note that you probably have permanently deleted your data doing so, so you should check "manually" if your data is present before going further.

What you want is simply to swap the 'w' with 'r'to open it in read mode.

Solution 2:[2]

Try:

with ZipFile('out.zip','w') as zip: 
    zip.write(latest_file) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 balderman