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>

效果图

相关推荐
该用户已不存在2 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP4 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780519 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i9 小时前
python中类的基本结构、特殊属性于MRO理解
python
liwulin050610 小时前
【ESP32-CAM】HELLO WORLD
python
Doris_202310 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202310 小时前
Python 模式匹配match case
前端·后端·python
这里有鱼汤11 小时前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
大模型真好玩11 小时前
深入浅出LangGraph AI Agent智能体开发教程(五)—LangGraph 数据分析助手智能体项目实战
人工智能·python·mcp
测试老哥11 小时前
Selenium 使用指南
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例