簡體   English   中英

讀取 csv 文件時出現問題 Python Flask 應用程序

[英]Problem with reading csv file Python Flask Application

我創建了一個 Python Flask 應用程序。 它讀取salary.csv文件並從該文件輸出一些數據。 現在,只要salary.csv 文件位於app.py 所在的同一文件夾中,我的應用程序就可以正常工作。 但是如果我沒有salary.csv 在同一個文件夾中並嘗試上傳它,它會給我這個錯誤 FileNotFoundError

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

應用程序.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)

索引.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>```

這是因為 Pandas 正在嘗試讀取本地文件而不是您提交的文件。

您需要訪問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