Python函数无法找到下载文件夹中最新.zip文件的问题排查
问题:查找下载文件夹最新ZIP文件时出现文件未找到错误
我正在编写一个程序,其中一部分功能是查找下载文件夹中最新的ZIP文件。编写函数后调用时出现文件未找到错误,但错误信息引用的确实是下载文件夹里最新的ZIP文件:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'CaseBuilderHistReport.1.31.2023.03.15.16.zip'
对应的函数代码如下:
def copy_latestfile(): #Get downloads folder path #downloads_folder_path = os.path.expanduser('~/Downloads') downloads_folder_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Downloads') #Define the copy location copy_location = '/Documents/Python/UCX Portal - Walmart/Data' #Get list of files in the download folder files_in_dir = os.listdir(downloads_folder_path) #Get only zip files from download folder zip_files = [file for file in files_in_dir if file.endswith('.zip')] #sort the list of files based on the date the file was created sort_files = sorted(zip_files,key=os.path.getctime) #get the most recent file and store it in a variable latest_file = max(zip_files) #copy the most recent file to the destined working location shutil.copy(latest_file)
问题原因分析
- 文件路径不完整:
os.listdir返回的只是文件名,不是完整路径。直接用仅含文件名的latest_file调用shutil.copy时,程序会在当前工作目录查找文件,而非下载文件夹,导致找不到文件。 - 最新文件判断错误:
max(zip_files)是按文件名的字符串字典序取最大值,不是按文件创建时间取最新文件。你已经写了按创建时间排序的代码,但未使用生成的sort_files变量。 - 目标路径错误:Windows系统中,以
/开头的路径会被解析为根目录,而非用户目录下的Documents,路径指向错误。 shutil.copy参数缺失:该函数需要两个参数(源文件路径、目标路径),你只传入了一个。
修复后的代码
import os import shutil def copy_latestfile(): # 获取下载文件夹完整路径 downloads_folder_path = os.path.join(os.environ['USERPROFILE'], 'Downloads') # 定义目标路径,拼接用户目录确保Windows下路径正确 copy_location = os.path.join(os.environ['USERPROFILE'], 'Documents', 'Python', 'UCX Portal - Walmart', 'Data') # 确保目标目录存在,不存在则创建 os.makedirs(copy_location, exist_ok=True) # 获取下载文件夹中所有文件的完整路径 all_files = [os.path.join(downloads_folder_path, file) for file in os.listdir(downloads_folder_path)] # 筛选出ZIP文件 zip_files = [file for file in all_files if file.endswith('.zip')] if not zip_files: print("下载文件夹中没有ZIP文件") return # 按文件创建时间排序,取最后一个元素作为最新文件 zip_files_sorted = sorted(zip_files, key=os.path.getctime) latest_file = zip_files_sorted[-1] # 复制文件到目标路径,传入源和目标两个参数 shutil.copy(latest_file, copy_location) print(f"已成功复制最新文件:{os.path.basename(latest_file)} 到 {copy_location}")
关键修复点
- 全程使用完整文件路径,避免当前工作目录的影响。
- 用
sorted结合os.path.getctime排序后取最后一个元素,替代错误的max(zip_files),确保取到真正的最新文件。 - 用
os.path.join拼接目标路径,适配Windows系统的路径规则。 - 调用
shutil.copy时传入完整的源路径和目标路径,同时提前创建目标目录防止报错。
内容的提问来源于stack exchange,提问作者bechele
相关产品推荐
相关产品推荐

