-4

I want, before uploading a file in image folder, to check if the file in the folder already exists or not. If the file already exists it should show a message.

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)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 4
    Probably want to take a look at [os.path.isfile](https://docs.python.org/3/library/os.path.html#os.path.isfile) or [os.path.exists](https://docs.python.org/3/library/os.path.html#os.path.exists). – Scratch'N'Purr Oct 22 '18 at 06:44
  • Please have a look here https://stackoverflow.com/questions/10978869/safely-create-a-file-if-and-only-if-it-does-not-exist-with-python – bak2trak Oct 22 '18 at 06:49

1 Answers1

2

You can check whether a path exists or not by using os.path.exists method, it returns True if the path passed as a parameter exists and returns False if it doesn't.

For instance: If you want to check if there is any file named hello.c in the current working directory, then you can use the following code:

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

Or You can use the absolute path too

For instance: If you want to check if there is any folder named Users in your C drive then you can use the following code:

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
letsintegreat
  • 3,328
  • 4
  • 18
  • 39