简体   繁体   English

在“ while”循环内写入.csv文件

[英]writing into .csv-file inside of “while”-loop

By using 通过使用

result = open("data/"+ name + "_" + timestamp + ".csv", "w")
result.write("time; data1; data2; data3 \n")`

I open a file and fill it with the column identifiers. 我打开一个文件,并用列标识符填充它。

Using 运用

while True:
    timestamp = time.strftime("%H:%M:%S", time.localtime())
    data1,data2,data3 = device.fetchData()

    result.write(timestamp +";"+ str(data1) +";"+ str(data1) +";"+ str(data3) +"\n")
    time.sleep(seconds)

the .csv-file should be filled with measuring data. .csv文件应填充测量数据。 The problem now is, that if I check the file after exiting the script, it's completely empty , not even the column identifiers are present. 现在的问题是,如果我在退出脚本后检查文件,则该文件完全为空 ,甚至没有列标识符。 However, if I use a for-loop, it works like it should. 但是,如果我使用for循环,它会像应该的那样工作。

Very strange for my understanding. 我的理解很奇怪。

I assume you want to leave this program running indefinitely to collect data from some kind of sensor, and so I suspect the issue is the default buffering from your open() call. 我假设您想让该程序无限期地运行以从某种传感器收集数据,因此我怀疑问题是来自open()调用的默认缓冲。

Firstly, you should almost always be using a "with" block like @Spirine suggests, but in your case a slight modification is in order: 首先,您应该几乎始终使用@Spirine建议的“ with”块,但是在您的情况下,需要进行一些小的修改:

with open("data/"+ name + "_" + timestamp + ".csv", "w", 1) as result:

The , 1 at the end indicates line buffering, meaning that Python will write the file to disk at the end of each line. 末尾的, 1表示行缓冲,这意味着Python将在每行末尾将文件写入磁盘。 Also, consider using str.format() to make it a bit more polished: 另外,请考虑使用str.format()使它更加优美:

log_line_template = "{ts:%H:%M:%S};{d1};{d2};{d3}\n"
filename = "data/{n}_{ts:%H_%M_%S}.csv".format(n=name, ts=datetime.now())

with open(filename, "w", 1) as result:
    result.write("time; data1; data2; data3 \n")`

    while True:
        data1,data2,data3 = device.fetchData()
        result.write(log_line_template.format(
            ts=datetime.now(), data1, data2, data3
        ))
        time.sleep(seconds)

If your file isn't correctly written it's because you're program is incorrectly stopped: to escape of the while loop, what do you do ? 如果您的文件未正确写入,那是因为您的程序未正确停止:要退出while循环,该怎么办? If you don't want to modify your code too much, you could just use the open context manager: 如果您不想过多修改代码,则可以使用open上下文管理器:

with open("data/"+ name + "_" + timestamp + ".csv", "w") as result:
    result.write("time; data1; data2; data3 \n")`

    while True:
        timestamp = time.strftime("%H:%M:%S", time.localtime())
        data1,data2,data3 = device.fetchData()

        result.write(timestamp +";"+ str(data1) +";"+ str(data1) +";"+ str(data3) +"\n")
        time.sleep(seconds)

As it, no matter what happens, your file will be correctly closed in the end of your program. 这样,无论发生什么情况,您的文件都将在程序末尾正确关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM