简体   繁体   English

读取 csv 文件时出现问题 Python Flask 应用程序

[英]Problem with reading csv file Python Flask Application

I created a Python Flask App.我创建了一个 Python Flask 应用程序。 It reads salary.csv file and outputs some data from that file.它读取salary.csv文件并从该文件输出一些数据。 Right now, my app works perfectly fine as long as the salary.csv file is inside the same folder where app.py is located.现在,只要salary.csv 文件位于app.py 所在的同一文件夹中,我的应用程序就可以正常工作。 But If I don't have salary.csv in the same folder and try to upload it, it gives me this error FileNotFoundError但是如果我没有salary.csv 在同一个文件夹中并尝试上传它,它会给我这个错误 FileNotFoundError

FileNotFoundError: [Errno 2] File salary.csv does not exist: 'salary.csv' FileNotFoundError:[Errno 2] 文件薪水.csv 不存在:'salary.csv'

app.py应用程序.py

import pandas
app = Flask(__name__)

@app.route('/')


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

@app.route('/', methods=['POST'])

def index_post():
    if request.method == 'POST':
#Storing salaries.csv data into a pandas dataframe
        req = request.form['fileToUpload']
        df = pandas.read_csv(req)
#Just calculating some data from dataframe 
        base_pay_MEAN = "{:.2f}".format(df['BasePay'].mean())
        base_pay_MAX = "{:.2f}".format(df['BasePay'].max())
        base_pay_MIN = "{:.2f}".format(df['BasePay'].min())

        overtime_MAX = df['OvertimePay'].max()
        highest_paid_Person_NAME = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['EmployeeName']
        highest_paid_Person_SALARY = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['TotalPayBenefits']
        highest_paid_Person_JOB = (df[df['TotalPayBenefits'] == max(df['TotalPayBenefits'])]).iloc[0]['JobTitle']

        lowest_paid_Person_NAME = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['EmployeeName']
        lowest_paid_Person_SALARY = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['TotalPayBenefits']
        lowest_paid_Person_JOB = (df[df['TotalPayBenefits'] == min(df['TotalPayBenefits'])]).iloc[0]['JobTitle']
        num_Unique_Jobs = df['JobTitle'].nunique()
        most_common_jobs = df.groupby('JobTitle').count().sort_values(by='Id', ascending=False)['Id'].head(3)        

#Returning the data to webpage
        return render_template('index.html',
        base_pay_Title="Basepay",
        base_pay_MEAN=( "Mean: $" + str(base_pay_MEAN)),
        base_pay_MAX=( "Max: $" + str(base_pay_MAX)),
        base_pay_MIN=( "Min: $" + str(base_pay_MIN)),
        over_time_Title="Overtime",
        over_time_MAX=("Max: $" + str(overtime_MAX)),
        highest_paid_Title = "Highest Paid",
        highest_paid_person=("Name: " + str(highest_paid_Person_NAME)),
        highest_paid_job=("Job: " + str(highest_paid_Person_JOB)),
        highest_paid_salary=("Salary: $" + str(highest_paid_Person_SALARY)),
        lowest_pay_Title = "Lowest Paid",
        lowest_paid_person=("Name: " + str(lowest_paid_Person_NAME)),
        lowest_paid_job=("Job: " + str(lowest_paid_Person_JOB)),
        lowest_paid_salary=("Salary: $" + str(lowest_paid_Person_SALARY))
        )
    else:
        render_template('index.html')

if __name__ == '__main__':
   app.run(host="localhost", port=7000, debug=True)

index.html索引.html

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="static/main.css">
    </head>

    <body>
        <div class="container">
            <h1>
                Some Title
            </h1>

            <p>Please upload your CSV file. The values containing addresses should be in a column named <em>address</em> or <em>Address</em></p>
            <form method='POST'>
                <input type="file" name="fileToUpload" id="fileToUpload">
                <button id="download">Submit</button>
            </form>
            <div class="results">
                <h3 class="base-pay">{{base_pay_Title}}</h3>
                <p class="base-pay-mean">{{ base_pay_MEAN }}</p>
                <p class="base-pay-high">{{base_pay_MAX}}</p>
                <p class="base-pay-low">{{base_pay_MIN}}</p>

                <h3 class="over-time">{{over_time_Title}}</h3>
                <p class="over-time-max">{{over_time_MAX}}</p>

                <h3 class="highest-paid">{{highest_paid_Title}}</h3>
                <p class="highest-paid-person">{{highest_paid_person}}</p>
                <p class="highest-paid-job">{{highest_paid_job}}</p>
                <p class="highest-paid-salary">{{highest_paid_salary}}</p>


                <h3 class="lowest-paid">{{lowest_pay_Title}}</h3>
                <p class="lowest-paid-person">{{lowest_paid_person}}</p>
                <p class="lowest-paid-job">{{lowest_paid_job}}</p>
                <p class="lowest-paid-salary">{{lowest_paid_salary}}</p>


            </div>
        </div>
    </body>
</html>```

That is happening because Pandas is trying to read a local file instead of your submitted file.这是因为 Pandas 正在尝试读取本地文件而不是您提交的文件。

Instead of reading the form dictionary, you need to access the files dictionary and pass its content to a Pandas DataFrame您需要访问files字典并将其内容传递给 Pandas DataFrame,而不是读取form字典

req = request.files.get('fileToUpload')
df = pandas.read_csv(req)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM