(45条消息) flask 读取文件夹文件,展示在页面,可以通过勾选删除_U盘失踪了的博客-CSDN博客
针对上面的功能再优化
项目结构
app.py
import os
import shutil
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
def generate_file_tree(path):
root = {
'name': os.path.basename(path),
'type': 'directory',
'children': []
}
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
child = generate_file_tree(item_path)
else:
child = {
'name': item,
'type': 'file'
}
root['children'].append(child)
return root
def delete_selected_files_and_dirs(path, file_tree):
selected_files = request.form.getlist('file-checkbox')
for item in file_tree['children']:
item_path = os.path.join(path, item['name'])
if item['type'] == 'file':
if item['name'] in selected_files:
os.remove(item_path)
elif item['type'] == 'directory':
if item['name'] in selected_files:
shutil.rmtree(item_path)
else:
delete_selected_files_and_dirs(item_path, item)
@app.route('/', methods=['GET', 'POST'])
def index():
if not os.path.isdir('testfile'):
os.makedirs('testfile')
file_tree = generate_file_tree('testfile')
if request.method == 'POST':
delete_selected_files_and_dirs('testfile', file_tree)
return redirect(url_for('index')) # 重定向到相同的URL
return render_template('index.html', file_tree=file_tree)
if __name__ == '__main__':
app.run()
templates / index.html
File Manager
File Manager
效果图
File Manager
File Manager
File Manager
File Manager