检查特定文件夹中是否已存在文件

时间:2018-10-22 06:39:33

标签: python file flask werkzeug os.path

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

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)

1 个答案:

答案 0 :(得分:0)

您可以使用path方法检查os.path.exists是否存在,如果存在作为参数传递的路径,则返回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

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

例如:如果要检查C驱动器中是否有任何名为Users的文件夹,则可以使用以下代码:

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