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>

效果图

相关推荐
weixin_5394467820 小时前
使用Java HttpServletResponse和JavaScript Fetch下载文件
java·javascript·python
CTA终结者20 小时前
Python 写期货自动交易:行情下单与成交回报怎么组织
开发语言·python·区块链
倾一生爱恋换一世纯真20 小时前
接口自动化测试框架搭建流程
python
abcy07121321 小时前
python flask app.py里的接口放在别的目录下图文教程
python
弹简特21 小时前
【零基础学Python】08-Python面向对象之封装、多态和函数进阶
开发语言·python
专注VB编程开发20年21 小时前
工控上位机开发为什么固死.net 4.5.2sdk?适配win7
python·信息可视化·c#
CC数学建模21 小时前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
Kobebryant-Manba21 小时前
安装cuda
pytorch·python·深度学习·conda·numpy
小何code21 小时前
【Python零基础入门】第10篇:Python列表方法与应用实例
数据库·人工智能·python
CC数学建模21 小时前
2026第八届中青杯全国大学生数学建模竞赛B题:AI生成内容的质量评估与参数优化完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模