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>

效果图

相关推荐
热爱编程的OP9 分钟前
Numpy常用库方法总结
开发语言·python·numpy
cliffordl16 分钟前
ReportLab 导出 PDF(文档创建)
开发语言·python·pdf
纪元A梦21 分钟前
华为OD机试真题——跳格子3(2025A卷:200分)Java/python/JavaScript/C++/C语言/GO六种最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
水w28 分钟前
【Python爬虫】简单案例介绍2
开发语言·爬虫·python
田野与天1 小时前
jupyter 文件浏览器,加强版,超好用,免费exe
ide·python·jupyter
选与握2 小时前
pytorch使用c++/cuda扩展
pytorch·python·c++/cuda
七七知享2 小时前
Python深度学习实现验证码识别全攻略
开发语言·python·深度学习·程序人生·程序员·开发·验证码
TOWNST3 小时前
Python Selenium 一小时速通教程
开发语言·python·selenium
张小凡vip3 小时前
pycharm已有python3.7,如何新增Run Configurations中的Python interpreter为python 3.9
ide·python·pycharm
小白鼠零号3 小时前
记录 | Pycharm中如何调用Anaconda的虚拟环境
ide·python·pycharm