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>

效果图

相关推荐
databook20 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室20 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python