Python使用读取然后写入文件的方法计算工作表上的值

Python使用读取然后写入文件的方法计算工作表上的值,python,csv,pandas,data-structures,Python,Csv,Pandas,Data Structures,你好,我是web应用程序开发的新手。我正在尝试制作一个应用程序,它可以处理csv文件 让我先粘贴代码,然后再在下面陈述我的问题: #!/usr/bin/env python import os import pandas as pd from flask import Flask, request,render_template, redirect, url_for, send_from_directory from werkzeug.utils import secure_filename

你好,我是web应用程序开发的新手。我正在尝试制作一个应用程序,它可以处理csv文件

让我先粘贴代码,然后再在下面陈述我的问题:

#!/usr/bin/env python
import os
import pandas as pd
from flask import Flask, request,render_template, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename





# create app
app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = '/home/Firiyuu77/mysite/uploads'
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','csv','xlsx'])

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']


@app.route('/')
def main():
    return render_template('index.html')

# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
    # Get the name of the uploaded file
    file = request.files['file']
    # Check if the file is one of the allowed types/extensions
    if file and allowed_file(file.filename):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)
        # Move the file form the temporal folder to
        # the upload folder we setup
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # Redirect the user to the uploaded_file route, which
        # will basicaly show on the browser the uploaded file
        return redirect(url_for('uploaded_file',
                                filename=filename))

# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(
        host="0.0.0.0",
        port=int("80"),
        debug=True
    )


#--------------------------------------------------------

#--------------------------------------------------------

#--------------------------------------------------------UNFINISHED PART

def forecastvalues():


  fileName = "test.csv"
  records = pd.read_csv(fileName, header=None, nrows=5)

  for i in records:
    rem = records.iloc([i], [0])
    sold1 = records.iloc([i], [1])
    sold2 = records.iloc([i], [2])

    rem = int(rem)
    sold1 = int(sold1)
    sold2 = int(sold2)
    result = forecast(rem,sold1,sold2)
    records.set_value([i], [4], result)
    pd.to_csv('test.csv')





#--------------------------------------------------------
#
#
#
#
# ------------------------------------------------------------
# MAIN Program
# ------------------------------------------------------------



#------------------------------------------------------------------------------------------------







def calculate(r,t,l):
    return ((l+t)/2)*3


def forecast(rem, sold1, sold2):


     if (rem == 0 and sold1 == 0 and sold2 ==0): #All ZERO
         return 15
     elif (rem == 0 and sold1 == 0 and sold2 < 10): #ALL FOR ONE PRODUCT VALUE
         return sold2*3
     elif (rem == 0 and sold1 < 10 and sold2 ==0):
         return sold1*3
     elif (rem < 10 and sold1 == 0 and sold2 == 0):
         return rem*3
     #END FOR ONE PRODUCT VALUE
     elif (rem>= 10 and  sold1>=10 and sold2>=10):

          if((rem/3)>=(sold1+10) or (rem/3)>=(sold1+10)):
              return 0
          else:
              return calculate(rem,sold1,sold2)-rem
     elif (rem<10 and sold1<10 and sold2<10):
         return calculate(rem,sold1,sold2)
     elif (rem == 0 and sold1>=10 and sold2>=10):
         return calculate(rem,sold1,sold2)
     else:
         return sold1






@app.route('/forecaster', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        # show html form
        return '''
            <form method="post">

        <h3>Type in the remaining stocks: </h3>        <input type="text" name="remaining" />
<br/>
        <h3>Type in the stocks for the past month: </h3>        <input type="text" name="sold1" />
<br/>
       <h3>Type in the stocks for the the month before the past month: </h3>         <input type="text" name="sold2" />
<br/>
<br/>
                <input type="submit" value="forecast" />
            </form>
        '''
    elif request.method == 'POST':
        # calculate result
        rem = int(request.form.get('remaining'))
        sold1 = int(request.form.get('sold1'))
        sold2 = int(request.form.get('sold2'))

        result = forecast(rem,sold1,sold2)

        return '<h1>Result: %s</h1>' % result
当程序处理完该文件时,将该文件复制到此输出

1 2 1 result
1 3 1 result
1 2 2 result

但它似乎对csv文件没有影响?我写了测试csv的名称作为文件名,以便测试它。我的工作有什么问题吗?还是我实施的方式不对?我用熊猫的备忘单做代码

您正在调用
pd.to_csv('test.csv')
,但我不相信这会起作用,因为没有
pandas.to_csv
方法。然而,有一个
pandas.DataFrame.to_csv
方法,它将完成您试图完成的任务。你需要打电话

records.to_csv('test.csv')

您好,谢谢您指出这一点,我更新了它,但我得到了以下回溯:
文件/home/firiyu77/mysite/flask_app.py”,第56行,在debug=True文件/usr/local/lib/python2.7/dist packages/flask/app.py”中,第843行,在run\u simple(主机、端口、self、**选项)文件/usr/local/lib/python2.7/dist packages/werkzeug/service.py中,第677行,在运行简单s.bind((主机名,端口))文件“/usr/lib/python2.7/socket.py”中,第224行,在meth return getattr(self.\u sock,name)(*args)
中,您认为我正确地执行了循环吗?是的:(不幸的是,这看起来像一个烧瓶错误,在更改为
to_csv
调用之前,你能运行这个吗?是的。我想也是同样的错误。我想我能成功地安装pandas,因为它没有问题。你觉得我的代码怎么样?我真的不舒服,我在cmd上运行它,但我当我把它放在Pythonywhere上时,它的工作方式不同,它似乎不会影响上传的文件。
records.to_csv('test.csv')