Python - 无法找到要解压缩的下载文件

Python - Can't locate downloaded file to unzip

使用 selenium,我能够自动下载 zip 文件并将其保存到指定目录。但是,当我尝试解压缩文件时,遇到了一个问题,我似乎无法找到最近下载的文件。如果有帮助,这是与下载和解压缩过程相关的代码块:

# Click on Map Link
driver.find_element_by_css_selector("input.linksubmit[value=\"▸ Map\"]").click()
# Download Data
driver.find_element_by_xpath('//*[@id="buttons"]/a[4]/img').click()

# Locate recently downloaded file
path = 'C:/.../Download'
list = os.listdir(path)
time_sorted_list = sorted(list, key=os.path.getmtime)
file_name = time_sorted_list[len(time_sorted_list)-1]

具体来说,这是我的错误:

Traceback (most recent call last):
  File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-89-3f1d00dac284>", line 3, in <module>
    time_sorted_list = sorted(list, key=os.path.getmtime)
  File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\genericpath.py", line 55, in getmtime
    return os.stat(filename).st_mtime
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'grid-m1b566d31a87cba1379e113bb93fdb61d5be5b128.zip'

我尝试通过删除代码并在目录中放置另一个文件来解决代码问题,我能够找到随机文件,但找不到最近下载的文件。谁能告诉我这是怎么回事?

首先,不要使用list作为变量名。这隐藏了 list 构造函数,使其无法在程序的其他地方使用。其次,os.listdir 不是 return 该目录中文件的完整路径。如果你想要完整路径,你可以做两件事:

您可以使用 os.path.join:

import zipfile


path = 'C:/.../Download'
file_list = [os.path.join(path, f) for f in os.listdir(path)]
time_sorted_list = sorted(file_list, key=os.path.getmtime)
file_name = time_sorted_list[-1]
myzip = zipfile.ZipFile(file_name)
for contained_file in myzip.namelist():
    if all(n in contained_file.lower() for n in ('corn', 'irrigation', 'high', 'brazil')):
        with myzip.open(contained_file) as f:
            # save data to a CSV file

您还可以使用 glob 模块中的 glob 函数:

from glob import glob
import zipfile


path = 'C:/.../Download'
file_list = glob(path+"/*")
time_sorted_list = sorted(file_list, key=os.path.getmtime)
file_name = time_sorted_list[-1]

myzip = zipfile.ZipFile(file_name)
for contained_file in myzip.namelist():
    if all(n in contained_file.lower() for n in ('corn', 'irrigation', 'high', 'brazil')):
        with myzip.open(contained_file) as f:
            # save data in a CSV file

两者都应该有效。