python - 有没有办法在不删除文件夹的情况下删除文件夹的所有内容?
问题描述
我尝试使用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")
但这似乎不起作用。谢谢
解决方案
正如@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}]")
推荐阅读
- node.js - 如何解决触发 Chromium 浏览器并使用 node.js Puppeteer 模块执行 Web 自动化时出现 NULL SID 登录的问题?
- arrays - 反应:“.map 不是函数”,我应该使用 object.keys 吗?
- automation - Oculus Quest 导航和模拟所需的 ADB 命令
- python - Cron Python 脚本在关机时执行任务
- sql - Athena 嵌套视图性能
- jenkins - Jenkins 测试无法打开 Excel
- istio - 我们已经在 GCP 中创建了 knative serverless 应用程序。我们正在尝试使用 istio 网格访问它
- php - 通过 PHP proc_open 调用 FFmpeg 总是会导致输出发送到 STDERR 而不是 STDOUT
- java - 为什么我保存的片段总是为空?
- android - Android 自动备份前台服务