python-3.x - 在 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'**
解决方案
如文档所述,os.listdir()
仅返回文件名。要统计文件(或实际使用它做任何其他事情),您必须使用以下命令重建完整路径os.path.join()
:
for filename in os.listdir(dirname):
filepath = os.path.join(dirname, filename)
modified_time = os.path.getmtime(filepath)
推荐阅读
- python - Flask 应用程序为来自公共 IP 的路由提供 404
- android - 在 rxJava 中压缩超过 9 个 Observable
- outlook-addin - Outlook 加载项 OWA ios 未加载
- python - 我的 self.canvas.clear() 函数不起作用,但方法中的其他代码运行
- python - 使用 Python 抓取分页
- curl - 卷曲保存下载,扩展名由内容类型确定
- css - 表单向上移动并与导航栏重叠
- laravel - Laravel 和 Vue.js。我无法修复我的代码
- powershell - 将调用命令脚本块与交换管理 shell 一起使用
- c# - 如何检测后退按钮单击并使webview返回