【问题标题】:Check if a file already exists in a particular folder [duplicate]检查特定文件夹中是否已存在文件[重复]
【发布时间】:2019-03-26 04:30:40
【问题描述】:

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

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)

【问题讨论】:

标签: python file flask werkzeug os.path


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多