Finding error python

可紊 提交于 2019-12-25 18:41:36

问题


If someone could aid me in finding my flaw, what I want the script to do is every minute a different random number is appended to the rows. The result I am getting just gives me the same number down the rows.

from openpyxl import Workbook
from openpyxl import load_workbook
import random
import schedule     
import time
import datetime     

def create_excel(info, info2):
    wb = Workbook()

    ws = wb.active

    n = 1
    ws.title = 'Test ' + str(n)

    ws['A1'] = 42

    wb.save('sample.xlsx')

    while n < 4:
        wb = load_workbook('sample.xlsx')
        ws = wb.active
        ws.append([info, info2])
        n += 1
        wb.save('sample.xlsx')


def main():
    print('Starting program now....')
    int = random.randint(55, 99)
    int2 = random.randint(1, 50)
    excel(int, int2)
    print('Finished program.')


m = 1
schedule.every(1).minute.do(main)
while m < 4:
    schedule.run_pending()
    time.sleep(60)
    m += 1

回答1:


The issue is with the line ws.append([info, info2]) which appends the same two values each time.

To append a new pair of integers on each occurrence of your while loop, you could implement a new function that generates a new pair of random integers.

This would work:

def generate_random_number():
    int1 = random.randint(55, 99)
    int2 = random.randint(1, 50)
    return int1, int2

def create_excel():
    wb = Workbook()
    ws = wb.active
    n = 1
    ws.title = 'Test ' + str(n)
    ws['A1'] = 42
    wb.save('sample.xlsx')
    while n < 4:
        wb = load_workbook('sample.xlsx')
        ws = wb.active
        ws.append(generate_random_number())
        n += 1
        wb.save('sample.xlsx')

def main():
    print('Starting program now....')
    create_excel()
    print('Finished program.')

m = 1
schedule.every(1).minute.do(main)
while m < 4:
    schedule.run_pending()
    time.sleep(60)
    m += 1


来源:https://stackoverflow.com/questions/41079663/finding-error-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!