python - 以选定的频率写入 csv 文件
问题描述
我想以选定的频率将加速度计数据写入 .csv 文件,假设每 20 毫秒一行。做这个的最好方式是什么?
这是我将用来写入文件的代码:
import csv
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow([bandymas,"Clockwise",timestamp,accX,accY,accZ])
注意:我知道我没有声明一些变量,这只是为了展示我正在使用的方法。
解决方案
这将是时间关键脚本的最佳实现:
from time import sleep
from random import randint
from datetime import datetime
# open in "a" mode is the fastest option because it does not waste time reading the file.
# and we should use the "with" context only at the begining to avoid precious time delays
with open('innovators.csv', 'a') as opened_file:
# the touple is the fastest reading object
# so we use it to pass to the writing function:
def append_to_file(file: type(open), row:tuple):
# using this format:
# [bandymas,"Clockwise",timestamp,accX,accY,accZ]
#file.write("%i,%s,%s,%i,%i,%i;\n" % row ) # csv is not standarized yet so this format could work on some computers
file.write("%i;%s;%s;%i;%i;%i,\n" % row ) # this is compatible with excel
# this would be the time precious operation
while True:
#get the values from a sensor (in this case we are simulating them):
now = datetime.now() # current date and time
row = (randint(-20, 100), "Clockwise", str(now), randint(50, 180), randint(100, 200), randint(10, 60))
#save the row to the file
append_to_file(opened_file, row)
sleep(1)
推荐阅读
- sql-server - 如何使用用户给出的模式和表名构建 sql 查询
- java - 如何模拟调用没有返回值的其他方法的方法
- react-native - 将文本标签添加到弧形 React Native
- java - 如何获取注解上方的注解
- swift - 为什么 UItableview 对象上不显示文本
- excel - 在主工作簿中打开工作表并将其复制到某些工作表
- typescript - 由作为参数提供的回调的返回类型提供的函数的返回类型
- reactjs - Apache 配置允许直接导航到 React 的客户端 URL
- reactjs - 如何在 React 中更改 App 组件的状态
- sql - 无法使用 unnest 函数分隔多列值