首页 > 解决方案 > 无法删除文件 - 获取 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)

标签: pythonfilenotfoundexception

解决方案


推荐阅读