项目结构
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>
效果图
文章来源:https://www.toymoban.com/news/detail-600625.html
文章来源地址https://www.toymoban.com/news/detail-600625.html
到了这里,关于Flask 创建文件目录,删除文件目录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!