我想在每次调用函数时附加一个excel文件。我该怎么做呢?例如,第一次调用该函数时,将电话号码和文本粘贴到第2行,然后在下次调用该函数时,将电话号码和文本粘贴到第3行,等等。我想要&#34 ; I"改变。
os.chdir("/Users/name/Desktop/name/name")
book = openpyxl.Workbook()
sheet = book.create_sheet("Sheet", 0)
sheet.cell(row=1, column=6).value = "Verification Code"
class func_with_memory:
i = 2
def write_to_ith_excelrow(self):
print ('i =', self.i)
self.i += 1
def receive_sms(self, i):
i = i+2
# Sender's phone numer
from_number = request.values.get('From')
# Receiver's phone number - Plivo number
to_number = request.values.get('To')
# The text which was received
text = request.values.get('Text')
# Print the message
print 'Message received - From: %s, To: %s, Text: %s' % (from_number, to_number, text)
# send 'Text' into an excel file
sheet.cell(row=i, column=6).value = text
book.save("numbers.xlsx")
return "Message received"
sms_to_xl = func_with_memory()
sms_to_xl.write_to_ith_excelrow()
答案 0 :(得分:0)
如果你希望函数自己管理这个计数功能,你必须定义一个类,你的函数作为一个成员函数,可以访问一个成员变量,你可以存储计数器值。
E.g。某事:
class func_with_memory: # define your class
i = 1
def write_to_ith_excelrow(self):
print('i =', self.i) # replace by meaningful code you want to process
self.i += 1
定义后,您可以使用此类:
In[1]: sms_to_xl = func_with_memory() # instantiate the class
In[2]: sms_to_xl.write_to_ith_excelrow() # first call of member function
i = 1
In[3]: sms_to_xl.write_to_ith_excelrow() # second call
i = 2
In[4]: sms_to_xl.write_to_ith_excelrow() # third call
i = 3
答案 1 :(得分:0)
为什么不使用全局变量?小心使用它们是好的,但在这种情况下它似乎是完全合适的。
import plivo, plivoxml
import openpyxl
from flask import Flask, request
import os
os.chdir("/Users/name/Desktop/name/name")
book = openpyxl.Workbook()
sheet = book.create_sheet("Sheet", 0)
sheet.cell(row=1, column=6).value = "Verification Code"
app = Flask(__name__)
xlsx_row_counter = 2
@app.route("/", methods=['GET','POST'])
def receive_sms():
global xlsx_row_counter
from_number = request.values.get('From')
to_number = request.values.get('To')
text = request.values.get('Text')
print 'Message received - From: %s, To: %s, Text: %s' % (from_number, to_number, text)
sheet.cell(row=xlsx_row_counter, column=6).value = text
book.save("numbers.xlsx")
xlsx_row_counter += 1
return "Message received", 200
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080)