Python Can';t删除文件-获取FileNotFound错误

Python Can';t删除文件-获取FileNotFound错误,python,filenotfoundexception,Python,Filenotfoundexception,我试图写一个程序,将删除一个特定文件夹内的文件 当我运行以下代码时,会出现错误: FileNotFoundError:[Errno 2]没有这样的文件或目录:'/Users/joshuamorse/Documents/Programming/python/deletefiles/1.txt 我的代码: import os, sys for filename in os.listdir('/Users/joshuamorse/Documents/programming/python/delete

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

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

FileNotFoundError:[Errno 2]没有这样的文件或目录:'/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]没有这样的文件或目录:'/Users/joshuamorse/Documents/programming/python/deletefiles/f2/

为什么最后一个文件夹只有在被错放时才包含在路径中?我将如何着手解决此问题,以便通过正确的路径

解决方案

由@ekhumoro提供

os.listdir()
不返回路径,只返回指定文件夹中的文件名

修正码

导入操作系统
dirpath='/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'
对于os.listdir(dirpath)中的文件名:
x=os.path.join(dirpath,文件名)
操作系统取消链接(x)

这是因为
listdir
还将列出您提供的路径下的所有子目录,这可能会有所帮助:
os.listdir
始终返回文件名列表,而不是完整路径。因此,您需要对os.listdir(dirpath)中的文件名执行
dirpath='/Users/joshuamorse/Documents/programming/python/deletefiles/f2d/'