Check if a file already exists in a particular folder [duplicate] - python

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Safely create a file if and only if it does not exist with Python
(3 answers)
Closed 4 years ago.
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)

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

Related

PIL.UnidentifiedImageError PIL.UnidentifiedImageError: cannot identify image file 'd:\\a/images/.pdf'

from PIL import Image
import PyPDF2
tess.pytesseract.tesseract_cmd = r'C:\Users\szaid\AppData\Local\Programs\Tesseract-OCR\tesseract'
translator=Translator()
project_dir = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__,
static_url_path='',
static_folder='static',
template_folder='template')
photos = UploadSet('photos', IMAGES)
pdf = UploadSet('pdf', DOCUMENTS)
app.config['DEBUG'] = True
app.config['UPLOAD_FOLDER']= 'images'
class Get(object):
def __init__(self, file): enter code here
if render_template('image.html'):
self.file = tess.image_to_string(Image.open(project_dir + '/images/'+ file))
elif render_template('pdf.html'):
self.file = PyPDF2.PdfFileReader(project_dir+'/pdff/'+ file)
And below, this is backend code to save the file in 'images' folder but its giving me an error.
I mean there is two different html pages and in both pages, there is an option to upload file and image. but dont know how to manage in flask...
#app.route('/pdf', methods=["GET","POST"])
def pdf():
if request.method == 'POST':
if 'pdf' not in request.files:
return 'there is no photo'
name1 = request.form['pdf-name'] + '.pdf'
pdf = request.files['pdf']
path = os.path.join(app.config['UPLOAD_FOLDER'], name1)
pdf.save(path)
TextObject = Get(name1)
return TextObject.file
return render_template('pdf.html')
error
You're getting this error because your path to the PDF file is wrong. You've added the file extension but the path is missing the file name. You also have a problem with your slashes in the path. A correct path would be like:
"D:\images\yourFileName.pdf"

Use url_for to create link to an excel file in output folder

I have one question about url_for Unable to open files in python flask- 404 not found. but was marked duplicate.
My requirement is very simple. To create an href link in the main page pointing to a file in the output folder. I tried almost all threads in SO for the answer seems not working for me. Im very new to python . Please help. Below is a sample code i have tried
from flask import Flask, redirect, url_for,send_from_directory
app = Flask(__name__)
#app.route('/main')
def index():
print 'test'
return '''Open file'''
#app.route('/out/<filename>')
def uploaded_file(filename):
print filename
return send_from_directory('./out/',
filename)
#app.route('/out/<filename>')
def uploaded_file2(filename):
print filename
return './out/'+filename
if __name__ == '__main__':
app.run(debug = True)
your app directory structure should be like this so this code would work. If the filename was not found in out folder then you will see "url not found":
app/
app.py
static/
out/
a.txt
templates/
index.html
from flask import Flask, render_template, redirect, url_for,send_from_directory
app = Flask(__name__)
app.config.update(
UPLOAD_FOLDER = "static/out/"
)
#app.route('/main')
def index():
print ('test')
return render_template('index.html')
#app.route('/out/<filename>')
def uploaded_file(filename):
print (filename)
return send_from_directory(app.config["UPLOAD_FOLDER"], filename)
#app.route('/showfilepath/<filename>')
def uploaded_file2(filename):
print (filename)
return app.config["UPLOAD_FOLDER"] + filename
if __name__ == '__main__':
app.run(debug = True)
# index.html
open file
# a.txt
hey there ...

Flask upload cannot find directory in server

I have problem with Flask upload in local machine code are working but when upload code to server using apache show error
IOError: [Errno 2] No such file or directory:
u'app/static/avatars/KHUON.S.png'
Code :
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = 'app/static/avatars'
app.config['MAX_CONTENT_LENGTH'] = 1 * 600 * 600
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/User/Profile', methods=['GET', 'POST'])
def upload_profile():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
else:
flash("File extension not allow.")
return redirect(url_for('upload_profile', upload='error'))
return render_template("profile.html")
Ok, in upload.py you could do something like
import os
absolute_path = os.path.abspath(UPLOAD_FOLDER+file_name)
os.path.abspath returns the absolute path from the given relative path.

Python - how to programmatically generate Index.HTML file to list contents of an uploads folder?

I got a web service that allows user to upload files to the "Uploads" folder. These files are accessible by name using the /uploads/filename.ext path. However, unless I know the precise filename, I cannot access files.
How can I programmatically generate and serve a webpage that will provide an index of all files in the /uploads folder if the user types /uploads?
from flask import Flask
from flask import Response, jsonify, request, redirect, url_for
import os
from werkzeug.utils import secure_filename
#configuration
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#retrieve uploads by name
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
################# AUDIO NOTES UPLOAD ####################
#app.route('/', methods=['GET', 'POST'])
def upload_file():
print 'upload file'
try:
os.stat(app.config['UPLOAD_FOLDER'])
except:
os.mkdir(app.config['UPLOAD_FOLDER'])
if request.method == 'POST':
file = request.files['file']
print 'filename: ' + file.filename
if file and allowed_file(file.filename):
print 'allowing file'
filename = secure_filename(file.filename)
print 'secure filename created'
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print 'file saved'
return redirect(url_for('uploaded_file',filename=filename))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
################## APP LAUNCH POINT ############################
if __name__ == '__main__':
app.run(host='0.0.0.0')
############################################################
Slightly off-topic, since the original question was for python, but you can generate a static HTML directory listing using tree in HTML output mode:
tree -H "/uploads" -L 1 > index.html
The option -L 1 limits the listing only for the current folder. Without it, the list will recursively include all the subfolders.
It is available in standard repos for most distros. On ubuntu you can install it with sudo apt install tree.
Related:
How can I create a simple index.html file which lists all files/directories?
It sounds like you need to list all of the files that are inside the Upload folder. Python's os.listDir() should be able to help you. I am using listDir to get all the names of the files, and then passing them to my view as a render parameter.
def get_files_from_directory(path):
list_of_files = []
if len(path) > 0:
list_of_files = [ f for f in listdir(path) if isfile(join(path,f)) ]
return list_of files
You could then do something like this:
#app.route('/uploads/<path>')
def list_uploads(path):
list_of_uploads = get_files_from_directory(path)
#render your template with this list_of_uploads.
My recommendation is that you don't give users the option to pass their own paths. This could be a huge security risk for you. Instead, create a URL like: 'http://www.yourwebsite.com/uploads/list'. Which will pass a path you set in your server-side code to get the files they want to look at. This will be much, much safer.

Flask - Errno 13 premission denied

I'm writing a small web page whose task is to let a user upload his input file and with uploading I want to execute my calculation program in python which will give me output for the user.
My code looks like this:
import os
import os.path
import datetime
import subprocess
from flask import Flask, render_template, request, redirect, url_for
from werkzeug import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'gro', 'doc', 'docx'])
current_time = datetime.datetime.now()
file_time = current_time.isoformat()
proper_filename = file_time
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
def run_script():
subprocess.call(['/home/martyna/Dropbox/programowanie/project_firefox/topologia.py', '/uploads/proper_filename'])
#app.route('/')
def index():
return render_template('index.html')
#app.route('/upload', methods = ['POST'])
def upload():
file = request.files['file']
if file and allowed_file(file.filename):
file.save(os.path.join(app.config['UPLOAD_FOLDER'], proper_filename))
run_script().start()
return "Thank you for uploading"
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0')
Uploading goes well, but the problem is that when I hit upload I get message OSError: [Errno 13] Permission denied and the line causing the problem is:
subprocess.call(['/home/martyna/Dropbox/programowanie/project_firefox/topologia.py', '/uploads/2014-05-16T22:08:19.522441'])
program topologia.py runs from command python topologia.py input_file
I have no idea how to solve that problem.
You have two problems:
Your script is probably not marked as executable. You can work around that by using the current Python executable path; use sys.executable to get the path to that.
You are telling the script to process /uploads/proper_filename, but the filename you actually upload your file to is not the same at all; you should use the contents of the string referenced by proper_filename instead.
Put these two together:
import sys
from flask import current_app
def run_script():
filename = os.path.join(current_app.config['UPLOAD_FOLDER'], proper_filename)
subprocess.call([
sys.executable,
'/home/martyna/Dropbox/programowanie/project_firefox/topologia.py',
filename])
You do not need to call .start() on the result of run_script(); you'll get an attribute error on NoneType. Just call run_script() and be done with it:
run_script()
Executing a script from a command line and from a server will not be done with the same permissions.
user#mycomputer:~$ ./script
In this exemple, ./script is launched by user. So if it does some inputs/outputs, the access rigths will depend on user rights.
When it is a server that runs the script, in your case Flask, it is probably www-data that launch the script. So the access rights are not the same.
So to create a file into a folder the user executing the script should have the permissions on the folder.

Categories