python - 无法删除文件 - 获取 FileNotFoundError
问题描述
我正在尝试编写一个程序来删除特定文件夹中的文件。
当我运行以下代码时,出现错误:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/Programming/python/deletefiles/1.txt
我的代码:
import os, sys
for filename in os.listdir('/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'):
print(filename)
x = os.path.realpath(filename) #not required but included so program would give more meaningful error
os.unlink(x)
当第 5 行被注释掉时,程序运行良好并列出文件夹中包含的所有文件。
我不明白为什么错误会切断f2d
目录路径中的最后一个文件夹()。此外,如果我错过键入路径中的最后一个文件夹,f2
则会产生以下错误:FileNotFoundError: [Errno 2] No such file or directory: '/Users/joshuamorse/Documents/programming/python/deletefiles/f2/
.
为什么最后一个文件夹只有在拼写错误的情况下才包含在路径中?我将如何解决这个问题以便通过正确的路径?
解决方案
由@ekhumoro 提供
os.listdir()
不返回路径,只返回指定文件夹中的文件名。
更正的代码
import os
dirpath = '/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'
for filename in os.listdir(dirpath):
x = os.path.join(dirpath, filename)
os.unlink(x)
解决方案
推荐阅读
- php - 自动完成 - 从 MySQL 数据库中检索结果
- asp.net - 将 asp.net 应用程序迁移到 Microsoft Edge 时出现问题(版本 91.0.864.70(官方版本)(64 位))
- node.js - 将 MERN 堆栈 docker 容器绑定到服务器的本地 ip 并使用 VPS 访问它
- parsing - 如何在 flex/lex 中更改动作之外的“开始条件”?
- c++ - 在 C++20 中进行复制列表初始化时是否需要移动省略?
- typescript - 如何在 ReactNative Auth0 - /authorize url 中添加自定义查询参数?
- angular - Angular mat-datepicker-header aria-label 本地化
- java - Chrome 浏览器 - 等待驱动程序服务器启动超时
- react-native - 组件不能包含子组件。如果要在图像顶部呈现内容,请考虑使用
零件 - c# - 计算数组的非空元素 - LINQ 性能问题