Python 如何删除文件夹的内容?
如何在Python中删除本地文件夹的内容Python 如何删除文件夹的内容?,python,file,Python,File,如何在Python中删除本地文件夹的内容 当前项目是针对Windows的,但我也希望看到*nix。为此,您最好使用os.walk() import os, shutil folder = '/path/to/folder' for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.pat
当前项目是针对Windows的,但我也希望看到*nix。为此,您最好使用
os.walk()
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
os.listdir()
无法区分文件和目录,您在尝试解除这些链接时很快就会遇到麻烦。有一个很好的例子,可以使用os.walk()
递归删除目录,并提示如何使其适应您的环境。您可以使用以下方法删除文件夹本身及其所有内容:
shutil.rmtree(路径,忽略错误=False,onerror=None)
删除整个目录树;路径必须指向目录(但不是指向目录的符号链接)。如果ignore_errors为true,则将忽略由于删除失败而导致的错误;如果为false或省略,则通过调用onerror指定的处理程序来处理此类错误,如果省略了,则会引发异常
扩展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))
您可以简单地执行以下操作:
import os
import glob
files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)
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))
当然,您可以在路径中使用其他筛选器,例如:/You/path/*.txt来删除目录中的所有文本文件。使用
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) or os.path.islink(file_object_path):
os.unlink(file_object_path)
else:
shutil.rmtree(file_object_path)
这:
- 删除所有符号链接
- 死链接
- 指向目录的链接
- 指向文件的链接
- 删除子目录
- 不删除父目录
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)
我知道这是一个老线程,但我在python的官方网站上发现了一些有趣的东西。只是为了分享另一个删除目录中所有内容的想法。因为我在使用shutil.rmtree()时遇到一些授权问题,我不想删除目录并重新创建它。地址是原件。希望这能帮助别人
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 shutil
import os
shutil.rmtree(dirpath)
os.mkdir(dirpath)
作为一家公司:
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)是一个更健壮的解决方案,它还可以考虑文件和目录:
另一个解决方案:
import sh
sh.rm(sh.glob('/path/to/folder/*'))
注:如果有人否决了我的答案,我想在这里解释一下
shutil.rmtree()
可以用来删除目录树。我在自己的项目中使用过很多次。但是您必须意识到目录本身也将被shutil.rmtree()
删除。虽然这对某些人来说是可以接受的,但对于删除文件夹内容(没有副作用)来说,这不是一个有效的答案shutil.rmtree()
删除它,并使用os.mkdir()
重建它。您将得到一个空目录,其中包含默认值(继承的)所有者和模式位。虽然您可能有删除内容甚至目录的权限,但您可能无法在目录上设置原始所有者和模式位(例如,您不是超级用户)这是一个漫长而丑陋,但可靠而有效的解决方案 它解决了其他回答者没有解决的几个问题:
- 它正确地处理符号链接,包括不调用符号链接上的
(如果链接到目录,它将通过shutil.rmtree()
测试;甚至os.path.isdir()
的结果也包含符号链接目录)os.walk()
- 它可以很好地处理只读文件
clear\u dir()
):
只需使用操作系统模块列出然后删除即可
import os
DIR = os.list('Folder')
for i in range(len(DIR)):
os.remove('Folder'+chr(92)+i)
为我工作,任何问题都让我知道 针对有限的特定情况回答: 假设要在维护子文件夹树时删除文件,可以使用递归算法:
import os
def recursively_remove_files(f):
if os.path.isfile(f):
os.unlink(f)
elif os.path.isdir(f):
for fi in os.listdir(f):
recursively_remove_files(os.path.join(f, fi))
recursively_remove_files(my_directory)
也许有点离题,但我想很多人会发现它很有用。我通过在以下两个之间添加
time.sleep()
解决了rmtree
makedirs
的问题:
if os.path.isdir(folder_location):
shutil.rmtree(folder_location)
time.sleep(.5)
os.makedirs(folder_location, 0o777)
如果您使用的是*nix系统,为什么不利用system命令呢
import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)
使用下面的方法删除目录的内容,而不是目录本身:
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)
要删除目录及其子目录中的所有文件,而不删除文件夹本身,只需执行以下操作:
import os
import glob
files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)
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))
我很惊讶,没有人提到做这项工作的很棒的
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)
非常直观的方法:
import shutil, os
def remove_folder_contents(path):
shutil.rmtree(path)
os.makedirs(path)
remove_folder_contents('/path/to/folder')
删除文件夹中所有文件/删除所有文件的最简单方法
import os
files = os.listdir(yourFilePath)
for f in files:
os.remove(yourFilePath + f)
我想这个
import shutil, os
def remove_folder_contents(path):
shutil.rmtree(path)
os.makedirs(path)
remove_folder_contents('/path/to/folder')
import os
files = os.listdir(yourFilePath)
for f in files:
os.remove(yourFilePath + f)
import os
import glob
files = glob.glob(r'path/*')
for items in files:
os.remove(items)
directory
folderA
file1
folderB
file2
folderC
file3
import os
import glob
folders = glob.glob('./path/to/parentdir/*')
for fo in folders:
file = glob.glob(f'{fo}/*')
for f in file:
os.remove(f)
import os
for i in os.listdir():
os.remove(i)