首页 > 解决方案 > 是否可以使用 Python 每隔 1 分钟向 excel 中注入一个数字?

问题描述

目前,我有一个每 5 秒更新一次 Excel 工作表的代码。它会打印

0 400 800 800 800

1 400 800 800 800

2 400 800 800 800

我想弄清楚的是如何每隔 1 分钟将随机数添加到该列表中,例如,

0 400 800 800 800

1 **425** 800 800 800

2 400 800 800 800

这里显示的代码是我当前的代码,想知道是否有人可以在这里帮助我,非常感谢:)。

import csv
import random
import time

x_value = 0
total_1 = 400 #voltage
total_2 = 800 #current(1)
total_3 = 800 #current(2)
total_4 = 800 #current(3)

fieldnames = ["Timestamp", "Voltage", "[L1] Current(1)", "[L1] Current(2)", "[L1] Current(3)"]

with open('test 4.0.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames = fieldnames)
    csv_writer.writeheader()
    
while True:
    with open('test 4.0.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames = fieldnames)
        
        info = {
            "Timestamp": x_value,
            "Voltage": total_1,
            "[L1] Current(1)": total_2,
            "[L1] Current(2)": total_3,
            "[L1] Current(3)": total_4
            }
        csv_writer.writerow(info)
        print(x_value, total_1, total_2, total_3, total_4)
        
        x_value += 1

    time.sleep(5) #controls the speed of the loop eg. 1 = 1sec

标签: pythonpython-3.9

解决方案


是的,您可以通过添加一个简单的标志来指示电压值是否应该随机化。

在循环之前,您可以通过以下方式初始化标志

...
total_4 = 800 #current(3)
randomVoltageFlag = False # new flag
...

然后在你的循环中,检查标志是否为真并相应地分配值

While True:
    ...
    info = {
       ...
       "Voltage": random.randrange(200,500) if randomVoltageFlag else total_1,
       ...

最后,在循环结束时,您可以切换标志以将其翻转以进行下一次迭代

randomVoltageFlag = not randomVoltageFlag

完整修改的代码现在应该是

import csv
import random
import time

x_value = 0
total_1 = 400 #voltage
total_2 = 800 #current(1)
total_3 = 800 #current(2)
total_4 = 800 #current(3)
randomVoltageFlag = False # new flag

fieldnames = ["Timestamp", "Voltage", "[L1] Current(1)", "[L1] Current(2)", "[L1] Current(3)"]

with open('test 4.0.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames = fieldnames)
    csv_writer.writeheader()
    
while True:
    with open('test 4.0.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames = fieldnames)
        
        info = {
            "Timestamp": x_value,
            "Voltage": random.randrange(200,500) if randomVoltageFlag else total_1,
            "[L1] Current(1)": total_2,
            "[L1] Current(2)": total_3,
            "[L1] Current(3)": total_4
            }
        csv_writer.writerow(info)
        print(x_value, total_1, total_2, total_3, total_4)
        
        x_value += 1
        randomVoltageFlag = not randomVoltageFlag
    time.sleep(5) #controls the speed of the loop eg. 1 = 1sec

注意,这只是你的一个例子。它可以通过使用mod 运算符将标志替换为您的 x_value 来进一步优化%,但我将把这部分留给您尝试。


推荐阅读