Elijah Kalii
Elijah Kalii

Reputation: 21

Flask app. FileNotFoundError: [Errno 2] No such file or directory

I am trying to create my first Flask app where I am getting user data, doing a vlookup(merge) to add a few columns to the user, then doing a prediction on the whole dataframe. The problem is I cannot read my CSV data saved in the static folder so as to do the merge. Flask cannot see the csv files. Any help will be highly appreciated: Here is my code snippet

app = Flask(__name__, template_folder='templates')

def predict():
  if request.method == 'POST':

with open("static/region_map.csv", "r") as f1:
        region_map = f1.read()

FileNotFoundError: [Errno 2] No such file or directory: 'static/region_map.csv'

Upvotes: 0

Views: 2379

Answers (1)

Detlef
Detlef

Reputation: 8582

The values for paths set during configuration can be requested. These are absolute and should work. The static directory can be queried using the static_folder attribute.

import os

def predict():
    if request.method == 'POST':
        target = os.path.join(app.static_folder, 'region_map.csv')
        with open(target) as fp:
            region_map = fp.read()
    # ...

The open function opens the file and returns a file object. If you read the content in text mode using read, you will in fact get a string back. To get a dataframe from a csv file, it is advisable to use pandas.read_csv.

import os
import pandas as pd

def predict():
    target = os.path.join(app.static_folder, 'region_map.csv')
    df = pd.read_csv(target)
    # ...

Upvotes: 0

Related Questions