python - 检查文件是否已存在于特定文件夹中
问题描述
我想在上传图像文件夹中的文件之前检查文件夹中的文件是否已经存在。如果文件已经存在,它应该显示一条消息。
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)
解决方案
您可以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
或者您也可以使用绝对路径
例如:如果要检查Users
C 盘中是否有任何文件夹,则可以使用以下代码:
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
推荐阅读
- python-3.x - 将字典列表打印为表格
- c++ - 在 Stroustrup 的示例中,“return 1 : 2”中的冒号是什么意思?
- c# - 将用户路由到正确的区域
- python - 如何修复代码中的属性错误?
- android - 通过 Intent 添加时,Android 联系人数据是乱码
- python - 如何使用熊猫规范化这个 json?
- python - 在 matplotlib 散点图中向 X 标记添加边
- animation - 在 BottomSheet 中实现转换
- tensorflow - 使用 Estimator 接口通过预训练的 tensorflow 对象检测模型进行推理
- python - 为 matplotlib 散点图中的每个标记提供单独的 zorder 值