如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
当前回答
使用操作系统。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]
其他回答
我通过添加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)
我必须从一个父目录中的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删除目录中的所有文本文件。
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))