首页 > 解决方案 > 有没有办法在不删除文件夹的情况下删除文件夹的所有内容?

问题描述

我尝试使用shutil,但不是删除文件夹的内容,而是删除整个文件夹。

def delete_song():
    print("Deleting song")
    shutil.rmtree('./song_downloads')
    print("Deleted song")

但是它没有打印出“已删除的歌曲”。我也尝试使用 os.remove()

def delete_song():
    print("Deleting song")
    for file in os.listdir('./song_downloads'):
        os.remove(file)
        print("Deleted file")

但这似乎不起作用。谢谢

标签: pythondiscord.py

解决方案


正如@grysik 对您的问题的评论中所述,输出os.listdir()仅给出不合格的文件名(例如没有路径),因此调用os.remove()将无法在当前工作目录中找到文件,因此您需要通过路径也是如此。

以下将满足您的要求:

def delete_song(directory):
print("Deleting song...")
for f in os.listdir(directory):
    qualified_file=os.path.join(directory, f)
    os.remove(qualified_file)
    print(f"Deleted file [{qualified_file}]")

推荐阅读