删除目录中的所有文件 [英] Remove all files in a directory

查看:46
本文介绍了删除目录中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图删除某个目录中的所有文件给了我以下错误:

Trying to remove all of the files in a certain directory gives me the follwing error:

OSError: [Errno 2] 没有那个文件或目录:'/home/me/test/*'

OSError: [Errno 2] No such file or directory: '/home/me/test/*'

我正在运行的代码是:

import os
test = "/home/me/test/*"
os.remove(test)

推荐答案

os.remove() 对目录不起作用,os.rmdir() 会只在一个空目录上工作.而且 Python 不会像某些 shell 那样自动扩展/home/me/test/*".

os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory. And Python won't automatically expand "/home/me/test/*" like some shells do.

不过,您可以在目录中使用 shutil.rmtree() 来执行此操作.

You can use shutil.rmtree() on the directory to do this, however.

import shutil
shutil.rmtree('/home/me/test') 

小心,因为它会删除文件和子目录.

be careful as it removes the files and the sub-directories as well.

这篇关于删除目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆