如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
当前回答
要删除目录及其子目录中的所有文件,而不删除文件夹本身,只需执行以下操作:
import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath, topdown=False):
for file in files:
os.remove(os.path.join(root, file))
# Add this block to remove folders
for dir in dirs:
os.rmdir(os.path.join(root, dir))
# Add this line to remove the root folder at the end
os.rmdir(mypath)
其他回答
我很惊讶没有人提到做这项工作的很棒的pathlib。
如果你只想删除一个目录中的文件,它可以是一个联机程序
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 os
files = os.listdir(yourFilePath)
for f in files:
os.remove(yourFilePath + f)
我知道这是一个老线程,但我从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 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))