无法删除文件getting FileNotFoundError

2024-10-02 00:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个程序,将删除一个特定文件夹内的文件

当我运行以下代码时,会出现错误:

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)

Tags: 文件代码路径文件夹os错误filenameusers

热门问题