how to read a file in python flask

  • Last Update :
  • Techknowledgy :

And then try something like below in your code and let me know what happens

import os
from flask
import Flask, render_template, request, jsonify

basedir = os.path.abspath(os.path.dirname(__file__))
data_file = os.path.join(basedir, 'static/js/large.js')

WORDS = []
with open(data_file, "r") as file:
   for line in file.readlines():

app = Flask(__name__)

def index():
   return render_template("index.html")

def search():
   q = request.args.get("q")
words = [word
   for word in WORDS
   if word.startswith(q)
return jsonify(words)

Suggestion : 2

Post date April 2, 2022 ,© 2022 The Web Dev

For instance, we write

@app.route('/upload/', methods = ['POST'])
def upload():
   if request.method == 'POST':
   file = request.files["file"]
if file:
   df = pd.read_excel(files_excel["file"])

Suggestion : 3

Once you’re selecting a file, click Submit. The form’s post method calls the ‘/upload_file’ URL. The underlying function uploader() performs a save operation.,The default upload folder path and maximum size of uploaded files can be defined in the configuration settings for the Flask object.,It requires an HTML form whose enctype property is set to "multipart/form-data" to publish the file to the URL.The URL handler extracts the file from the request.files [] object and saves it to the required location.,The following code has a ‘/upload’ URL rule that displays’upload.html’ in the templates folder and the ‘/upload - file’ URL rule to invoke the upload () function to process the upload process.


   <form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" /> </form>


Suggestion : 4

Uploading Files A Gentle Introduction Improving Uploads Upload Progress Bars An Easier Solution

import os
from flask
import Flask, flash, request, redirect, url_for
from werkzeug.utils
import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'

app = Flask(__name__)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)['UPLOAD_FOLDER'], filename))
return redirect(url_for('uploaded_file',
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
   <input type=file name=file>
   <input type=submit value=Upload>
filename = "../../../../home/username/.bashrc"
>>> secure_filename('../../../../home/username/.bashrc')
from flask import send_from_directory

   def uploaded_file(filename):
   return send_from_directory(app.config['UPLOAD_FOLDER'],
from werkzeug.middleware.shared_data import SharedDataMiddleware
app.add_url_rule('/uploads/<filename>', 'uploaded_file',
app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
    '/uploads':  app.config['UPLOAD_FOLDER']

Suggestion : 5

I am writing my first flask application. I am dealing with file uploads, and basically what I want is to read the data/content of the uploaded file without saving it and then print it on the resulting page. Yes, I am assuming that the user uploads a text file always.,Right now, I am saving the file, but what I need is that 'a' variable to contain the content/data of the file .. any ideas?,What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?, Read file data without saving it in Flask

Here is the simple upload function i am using:

@app.route('/upload/', methods = ['GET', 'POST'])
def upload():
   if request.method == 'POST':
   file = request.files['file']
if file:
   filename = secure_filename(file.filename)['UPLOAD_FOLDER'], filename))
a = 'file uploaded'

return render_template('upload.html', data = a)