簡體   English   中英

如何在python中使用web.py處理上載的csv文件

[英]How to process uploaded csv file by using web.py in python

我正在嘗試為我的模型制作一個API。

我正在嘗試上傳csv文件,然后在csv中讀取數據,然后在API中使用模型進行預測。

我能夠上傳文件並保存在路徑中,但無法通過在python中使用web.py讀取csv數據進行預測

我已經保存了預測模型,並在此代碼中加載了預測數據。

upload.py

import web
from sklearn.externals import joblib
import requests

urls = ('/upload', 'Upload')

class Upload:

    def GET(self):

        web.header("Content-Type","text/html; charset=utf-8")

        return """<html><head></head><body>
                <form method="POST" enctype="multipart/form-data" action="">
                <input type="file" name="myfile" />
                <br/>
                <br/>
                <input type="submit" />
                </form>
                </body></html>"""    

    def POST(self):

        x = web.input(myfile=[])
        filedir = 'D:/API_CITY_PRED/Upload' # change this to the directory you want to store the file in.
        svmModel = open('D:/Model/model_city_id_predictor.pkl', 'rb')
        svmModel = joblib.load(svmModel)
        class_prediced = svmModel.predict(x)
        output = "Predicted City ID: " + str(class_prediced)
        print (output)

        if 'myfile' in x: # to check if the file-object is created
            filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
            fout = open(filedir +'/'+ filename,'wb') # creates the file where the uploaded file should be stored
            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete.

        return output
        raise web.seeother('/upload')

if __name__ == "__main__":
   app = web.application(urls, globals()) 
   app.run()

編輯1

# x is the input data

svmModel = open('D:/Model/model_city_id_predictor.pkl', 'rb') # SVM Model Imported svmModel = joblib.load(svmModel) # Model Loaded class_prediced = svmModel.predict(x) # here we are using to predict

請建議

采用

x = web.input(file={})
fout = open('path/to/location/', 'wb')  # creates the file where the uploaded file should be stored
fout.write(x.file.file.read())  # writes the uploaded file to the newly created file.
fout.close() 

這會將您的文件寫入指定的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM