Flask 创建文件目录,删除文件目录

项目结构

app.py

复制代码
from flask import Flask, render_template, request, redirect, url_for
import os

app = Flask(__name__)
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
FILE_DIR = os.path.join(BASE_DIR, 'testfile')


@app.route('/', methods=['GET', 'POST'])
def index():

    if request.method == 'POST':
        if 'create' in request.form:
            dirname = request.form.get('dirname')
            os.mkdir(os.path.join(FILE_DIR, dirname))
        elif 'delete' in request.form:
            dirname = request.form.get('dirname')
            os.rmdir(os.path.join(FILE_DIR, dirname))
        return redirect(url_for('index'))

    directories = os.listdir(FILE_DIR)
    return render_template('index.html', directories=directories)

if __name__ == '__main__':
    if not os.path.isdir('testfile'):
        os.makedirs('testfile')
    app.run(debug=True)

templates / index.html

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>File Manager</title>
</head>
<body>
    <h1>File Manager</h1>
    <form method="POST">
        <input type="text" name="dirname" placeholder="Directory Name">
        <input type="submit" name="create" value="Create Directory">
        <input type="submit" name="delete" value="Delete Directory">
    </form>
    <ul>
        {% for directory in directories %}
            <li>{{ directory }}</li>
        {% endfor %}
    </ul>
</body>
</html>

效果图

相关推荐
郭老二6 小时前
【Python】基本语法:装饰器语法糖@
python
_Jimmy_7 小时前
Agent常用检索器的详细介绍
python·langchain
小柯南敲键盘7 小时前
图片翻译API接入与自动化实现指南
运维·python·自动化
旅僧8 小时前
Q-learning(自用)
python·机器学习
Python大数据分析@8 小时前
曝梁文锋称「一度不想维护C端用户,奈何赶不走」,DeepSeek真不需要C端用户吗?可能会有啥影响吗?
python
艾斯特_9 小时前
工作流与多Agent协作:LangGraph、MCP和A2A的应用分层
人工智能·python·ai
IT小盘9 小时前
04-大模型流式输出原理-SSE与Python实现
开发语言·网络·人工智能·python
我叫黑大帅9 小时前
add()和 __add__() 写法哪个更好呢?
后端·python·面试
不如语冰9 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
柠檬味的Cat10 小时前
GEO优化系统哪个渠道商好
大数据·人工智能·python