Nic*_*tes 389
更新为仅删除文件并使用注释中建议的os.path.join()方法.如果您还想删除子目录,请取消注释elif语句.
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))
Run Code Online (Sandbox Code Playgroud)
Oli*_*Oli 216
试试shutil模块
import shutil
shutil.rmtree('/path/to/folder')
Run Code Online (Sandbox Code Playgroud)
描述:
shutil.rmtreeDocstring:递归删除目录树.
如果
shutil.rmtree(path, ignore_errors=False, onerror=None)设置,则忽略错误; 否则,如果shutil.rmtree设置,它被称为处理与参数的误差shutil.rmtree(path, ignore_errors=False, onerror=None)在那里shutil.rmtree为shutil.rmtree(path, ignore_errors=False, onerror=None),shutil.rmtree或shutil.rmtree(path, ignore_errors=False, onerror=None); path是导致它失败的那个函数的参数; 并且shutil.rmtree是由...返回的元组shutil.rmtree(path, ignore_errors=False, onerror=None).如果shutil.rmtree为false,shutil.rmtree(path, ignore_errors=False, onerror=None)则会shutil.rmtree引发异常.
小智 206
你可以这样做:
import os
import glob
files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)
Run Code Online (Sandbox Code Playgroud)
您当然可以在路径中使用其他过滤器,例如:/YOU/PATH/*.txt用于删除目录中的所有文本文件.
Ike*_*nez 74
扩展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))
Run Code Online (Sandbox Code Playgroud)
jgo*_*ers 44
使用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)
Run Code Online (Sandbox Code Playgroud)
Jon*_*Chu 17
这是迄今为止唯一的答案,其中:
码:
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
try:
shutil.rmtree(filepath)
except OSError:
os.remove(filepath)
Run Code Online (Sandbox Code Playgroud)
正如许多其他答案一样,这并不会尝试调整权限以启用文件/目录的删除.
小智 15
要删除文件夹中的所有文件,我使用:
import os
for i in os.listdir():
os.remove(i)
Run Code Online (Sandbox Code Playgroud)
fmo*_*lia 14
作为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)) ) )
Run Code Online (Sandbox Code Playgroud)
考虑文件和目录的更强大的解决方案也是(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)) )
Run Code Online (Sandbox Code Playgroud)
Roc*_*ite 14
注意:如果有人拒绝投票给我答案,我在这里有一些解释.
shutil.rmtree()可以用来删除目录树.我在自己的项目中多次使用它.但是你必须意识到目录本身也会被删除shutil.rmtree().虽然这对某些人来说可能是可以接受的,但它不是删除文件夹内容的有效答案(没有副作用).shutil.rmtree()并用它重建它os.mkdir().并且您将获得一个带有默认(继承)所有者和模式位的空目录.虽然您可能有权删除内容甚至目录,但您可能无法在目录上设置原始所有者和模式位(例如,您不是超级用户).这是一个漫长而丑陋但可靠而有效的解决方案.
它解决了其他问题无法解决的一些问题:
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")
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)
之前的评论还提到在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)
Run Code Online (Sandbox Code Playgroud)
要删除目录及其子目录中的所有文件,而不删除文件夹本身,只需执行以下操作:
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))
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 *nix 系统,为什么不利用 system 命令呢?
import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)
Run Code Online (Sandbox Code Playgroud)
我感到惊讶的是,没有人提到pathlib做这项工作很棒。
如果您只想删除目录中的文件,则可以将其作为一个文件
from pathlib import Path
[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()]
Run Code Online (Sandbox Code Playgroud)
要还递归地删除目录,您可以编写如下内容:
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)
Run Code Online (Sandbox Code Playgroud)
我曾经这样解决问题:
import shutil
import os
shutil.rmtree(dirpath)
os.mkdir(dirpath)
Run Code Online (Sandbox Code Playgroud)
我必须从单个父目录中的 3 个单独文件夹中删除文件:
directory
folderA
file1
folderB
file2
folderC
file3
Run Code Online (Sandbox Code Playgroud)
这个简单的代码对我有用:(我在 Unix 上)
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)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
我知道这是一个老线程,但我从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))
Run Code Online (Sandbox Code Playgroud)
又一个解决方案:
import sh
sh.rm(sh.glob('/path/to/folder/*'))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
440048 次 |
| 最近记录: |