如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
当前回答
我必须从一个父目录中的3个独立文件夹中删除文件:
directory
folderA
file1
folderB
file2
folderC
file3
这段简单的代码对我来说很管用:(我用的是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)
希望这能有所帮助。
其他回答
你可以简单地这样做:
import os
import glob
files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)
当然,您可以在路径中使用其他过滤器,例如:/ You / path /*.txt删除目录中的所有文本文件。
如果您正在使用*nix系统,为什么不利用system命令呢?
import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)
回答一个有限的、具体的情况: 假设你想在维护子文件夹树的同时删除文件,你可以使用递归算法:
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)
也许有点跑题,但我想很多人会觉得它很有用
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))
使用操作系统。Python 3.6+中的scandir和上下文管理器协议:
import os
import shutil
with os.scandir(target_dir) as entries:
for entry in entries:
if entry.is_dir() and not entry.is_symlink():
shutil.rmtree(entry.path)
else:
os.remove(entry.path)
Python的早期版本:
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
[shutil.rmtree(i) if os.path.isdir(i) and not os.path.islink(i) else os.remove(i) for i in contents]