怎么删除内容的一个文件夹在蟒蛇?
-
06-07-2019 - |
题
我怎么可以删除内容的一个当地的文件夹在蟒蛇?
目前的项目是为了窗口,但是我想看到*尼克斯。
解决方案
更新为仅删除文件并使用注释中建议的 os.path.join()
方法。如果您还想删除子目录,请取消注释 elif
语句。
import os, shutil
folder = '/path/to/folder'
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
#elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)
其他提示
尝试使用shutil模块
import shutil
shutil.rmtree('/path/to/folder')
描述:
shutil.rmtree(path,ignore_errors = False,onerror = None)
Docstring:递归删除 目录树。
如果设置了
ignore_errors
,则会出现错误 忽略;否则,如果设置了onerror
, 它被调用来处理错误 参数(func,path,exc_info)
其中func
是os.listdir
,os.remove
,或者 <代码> os.rmdir 代码>; path就是这个论点 导致它失败的功能;和exc_info
是由返回的元组 <代码> sys.exc_info()代码>。如果ignore_errors
是 false和onerror
是None
,an 异常被提出。
重要说明:请注意 shutil.rmtree()
不仅会删除目标文件夹的内容。它也会删除文件夹本身。
你可以这样做:
import os
import glob
files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)
您当然可以在路径中使用其他过滤器,例如:/YOU/PATH/*.txt用于删除目录中的所有文本文件。
扩展mhawke的回答这是我实施的。它会删除文件夹的所有内容,但不会删除文件夹本身。在Linux上使用文件,文件夹和符号链接进行测试,也可以在Windows上运行。
import os
import shutil
for root, dirs, files in os.walk('/path/to/folder'):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
使用 rmtree
并重新创建文件夹可以正常工作,但删除并立即重新创建网络驱动器上的文件夹时遇到错误。
使用walk的建议解决方案不起作用,因为它使用 rmtree
删除文件夹,然后可能尝试对以前在这些文件夹中的文件使用 os.unlink
。这会导致错误。
发布的 glob
解决方案也会尝试删除非空文件夹,从而导致错误。
我建议您使用:
folder_path = '/path/to/folder'
for file_object in os.listdir(folder_path):
file_object_path = os.path.join(folder_path, file_object)
if os.path.isfile(file_object_path):
os.unlink(file_object_path)
else:
shutil.rmtree(file_object_path)
这是唯一的答案迄今为止,其中:
- 删除所有象征意义的链接
- 死的链接
- 链接目录
- 文件的链接
- 删除子目录
- 不删除父目录
代码:
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
try:
shutil.rmtree(filepath)
except OSError:
os.remove(filepath)
作为许多其他的答案,这并不试图调整权限,以便去除文件的/目录。
作为oneliner:
import os
# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )
一个更强大的解决方案来计算文件和目录(2.7):
def rm(f):
if os.path.isdir(f): return os.rmdir(f)
if os.path.isfile(f): return os.unlink(f)
raise TypeError, 'must be either file or directory'
map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
注:在情况下的人投票,我的回答,我有些东西来解释这里。
- 每个人都喜欢短'n'简单的答案。然而,有时候现实也不是那么简单。
- 回到我的答案。我知道的
shutil.rmtree()
可用于删除一个目录树。我已经用了很多次,在我自己的项目。但是你必须意识到 该目录本身也将被删除shutil.rmtree()
.虽然这可能是可接受的对于一些人来说,这不是一个有效的答案 删除内容的一个文件夹(没有副作用). - 我会告诉你一个例子的副作用。假设你有一个目录 定制的 所有者和模式中的位,其中有很多内容。然后你删除它
shutil.rmtree()
重建它os.mkdir()
.你会得到一个空的目录 默认的 (继承)的所有者和模式的位,而不是。虽然你可能具有的权限,删除的内容,甚至目录,你不能设置回来的原始拥有者和模式的位上的目录(例如你不是一个超级用户). - 最后, 以患者和读码.它又长又丑(在视线),但证明是可靠和有效的(在使用)。
这里是一个漫长的和丑陋,但可靠和有效的解决方案。
它可以解决几个问题得不到解决,由其他answerers:
- 它正确地处理象征性的链接,包括不打电话
shutil.rmtree()
在一个象征性的链接(这将通过os.path.isdir()
测试,如果它链接目录;甚至是结果os.walk()
含有象征性的链接目录)。 - 它处理的只读文件。
这里的代码(唯一有用的功能 clear_dir()
):
import os
import stat
import shutil
# http://stackoverflow.com/questions/1889597/deleting-directory-in-python
def _remove_readonly(fn, path_, excinfo):
# Handle read-only files and directories
if fn is os.rmdir:
os.chmod(path_, stat.S_IWRITE)
os.rmdir(path_)
elif fn is os.remove:
os.lchmod(path_, stat.S_IWRITE)
os.remove(path_)
def force_remove_file_or_symlink(path_):
try:
os.remove(path_)
except OSError:
os.lchmod(path_, stat.S_IWRITE)
os.remove(path_)
# Code from shutil.rmtree()
def is_regular_dir(path_):
try:
mode = os.lstat(path_).st_mode
except os.error:
mode = 0
return stat.S_ISDIR(mode)
def clear_dir(path_):
if is_regular_dir(path_):
# Given path is a directory, clear its content
for name in os.listdir(path_):
fullpath = os.path.join(path_, name)
if is_regular_dir(fullpath):
shutil.rmtree(fullpath, onerror=_remove_readonly)
else:
force_remove_file_or_symlink(fullpath)
else:
# Given path is a file or a symlink.
# Raise an exception here to avoid accidentally clearing the content
# of a symbolic linked directory.
raise OSError("Cannot call clear_dir() on a symbolic link")
import os
import shutil
# Gather directory contents
contents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)]
# Iterate and remove each item in the appropriate manner
[os.remove(i) if os.path.isfile(i) or os.path.islink(i) else shutil.rmtree(i) for i in contents]
之前的评论还提到在Python 3.5+中使用os.scandir。例如:
import os
import shutil
with os.scandir(target_dir) as entries:
for entry in entries:
if entry.is_file() or entry.is_symlink():
os.remove(entry.path)
elif entry.is_dir():
shutil.rmtree(entry.path)
最好使用 os.walk()
。
os.listdir()
不区分文件和目录,您很快就会在尝试取消链接时遇到麻烦。有一个很好的例子,使用 os.walk()
递归删除目录这里,并提示如何使其适应您的环境。
我曾经这样解决问题:
import shutil
import os
shutil.rmtree(dirpath)
os.mkdir(dirpath)
我知道这是一个老线程,但我从python的官方网站上找到了一些有趣的东西。仅仅是为了分享另一个删除目录中所有内容的想法。因为在使用shutil.rmtree()时我有一些授权问题,我不想删除目录并重新创建它。地址原件为 http://docs.python.org/2/library /os.html#os.walk 。希望能帮助别人。
def emptydir(top):
if(top == '/' or top == "\\"): return
else:
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
又一个解决方案:
import sh
sh.rm(sh.glob('/path/to/folder/*'))
如果您使用的是* nix系统,为什么不利用系统命令?
import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)
我很惊讶没有人提到过很棒的 pathlib
来完成这项工作。
如果您只想删除目录中的文件,则可以是oneliner
from pathlib import Path
[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()]
要递归删除目录,您可以编写如下内容:
from pathlib import Path
from shutil import rmtree
for path in Path("/path/to/folder").glob("**/*"):
if path.is_file():
path.unlink()
elif path.is_dir():
rmtree(path)
我通过在 time.sleep()
之间添加 rmtree
makedirs
解决了这个问题:
if os.path.isdir(folder_location):
shutil.rmtree(folder_location)
time.sleep(.5)
os.makedirs(folder_location, 0o777)
回答有限的具体情况: 假设您想要在维护子文件夹树的同时删除文件,则可以使用递归算法:
import os
def recursively_remove_files(f):
if os.path.isfile(f):
os.unlink(f)
elif os.path.isdir(f):
map(recursively_remove_files, [os.path.join(f,fi) for fi in os.listdir(f)])
recursively_remove_files(my_directory)
也许稍微偏离主题,但我认为很多人会发现它很有用
假设要删除 temp_dir
,使用 os
的单行命令将是:
_ = [os.remove(os.path.join(save_dir,i)) for i in os.listdir(temp_dir)]
注意:这只是用于删除文件的1行 - “不删除目录。”
希望这会有所帮助。感谢。
使用下面的方法删除目录的内容,而不是目录本身:
import os
import shutil
def remove_contents(path):
for c in os.listdir(path):
full_path = os.path.join(path, c)
if os.path.isfile(full_path):
os.remove(full_path)
else:
shutil.rmtree(full_path)
只需这样做。这将删除目录内的所有文件以及子目录中的所有文件。不伤害任何文件夹/目录。在Ubuntu上运行良好,没有任何错误。
import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath):
for file in files:
os.remove(os.path.join(root, file))
这应该只是使用OS模块列出然后删除!
import os
DIR = os.list('Folder')
for i in range(len(DIR)):
os.remove('Folder'+chr(92)+i)
为我工作,任何问题都让我知道!