首页 > 解决方案 > 在 Python 中打开目录后出现错误

问题描述

import os
import time
import send2trash
import datetime
from tkinter import filedialog
from tkinter import *
import tkinter as tk

root = tk.Tk()
date = input("Enter your date: ")
date1 = time.strptime(date, '%Y-%m-%d')
date2 = time.mktime(date1)
dirname = filedialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')

for f in os.listdir(dirname):
       modified_time = os.path.getmtime(f)
    if modified_time < date2:
        send2trash.send2trash(f)

并且有一个错误:

File "C:\Users\FotoHub\Desktop\test0109.py", line 20, **in <module>
  modified_time = os.path.getmtime(f)**
File "C:\Users\FotoHub\AppData\Local\Programs\Python\Python37-32\Lib\genericpath.py", line 55, **in getmtime
  return os.stat(filename).st_mtime**

**builtins.FileNotFoundError: [WinError 2] The system cannot find the file specified: '322097.jpg'**

标签: python-3.x

解决方案


如文档所述,os.listdir()仅返回文件。要统计文件(或实际使用它做任何其他事情),您必须使用以下命令重建完整路径os.path.join()

for filename in os.listdir(dirname):
   filepath = os.path.join(dirname, filename)
   modified_time = os.path.getmtime(filepath)

推荐阅读