首页 > 解决方案 > 检查文件是否已存在于特定文件夹中

问题描述

我想在上传图像文件夹中的文件之前检查文件夹中的文件是否已经存在。如果文件已经存在,它应该显示一条消息。

from flask import Flask, render_template, request
from werkzeug import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'GIF'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
import os, os.path


APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLD = '/python/image/'
UPLOAD_FOLDER = os.path.join(APP_ROOT, UPLOAD_FOLD)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER



@app.route('/upload')
def load_file():
return render_template('upload.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
  f = request.files['file']   
  f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
  return 'file uploaded successfully'

if __name__ == '__main__':
app.run(debug = True)

标签: pythonfileflaskwerkzeugos.path

解决方案


您可以path通过使用os.path.exists方法检查a是否存在,True如果作为参数传递的路径存在则返回False,如果不存在则返回。

例如:如果要检查hello.c当前工作目录中是否有任何文件,则可以使用以下代码:

from os import path
path.exists('hello.c') # This will return True if hello.c exists and will return False if it doesn't

或者您也可以使用绝对路径

例如:如果要检查UsersC 盘中是否有任何文件夹,则可以使用以下代码:

from os import path
path.exists('C:\Users') # This will return True if Users exists in C drive and will return False if it doesn't

推荐阅读