python - 是否可以使用 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
解决方案
是的,您可以通过添加一个简单的标志来指示电压值是否应该随机化。
在循环之前,您可以通过以下方式初始化标志
...
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 来进一步优化%
,但我将把这部分留给您尝试。
推荐阅读
- php - AWS PHP PDO MySQL 连接问题 SQLSTATE[HY000] [2002]
- cmake - CMake:target_link_libraries 包含为 SYSTEM 以抑制编译器警告
- c++ - 调试 linux 源代码时发生错误:将源复制到远程机器时发生异常
- android - 滚动 Listview 时令人困惑的项目(回收站)
- php - 为什么即使我选择的数据存在,我的查询总是返回到 else 语句?
- python - Python显示额外的第一个括号
- javascript - socket.io 没有监听全局事件
- logic - 将下列语句表示为一阶谓词逻辑中的公式
- javascript - 如何为 nodemailer 附件使用相对路径?
- java - 使用 Spring Embebed 数据库的 JPA 未找到记录