简体   繁体   English

将值保存到每列 python

[英]Save value to each column python

I have the code like this:我有这样的代码:

Max = 0.0
while True:
    value = float(input("Please input a number: "))
    if value > Max:
        Max = value
        print("Max is ", Max)
    else:
        date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print("Max is ", Max)
        with open("test.csv", 'a', newline='') as file:
            writer = csv.writer(file, delimiter='\t')
            writer.writerow([date,Max])
            print("Write Max value to file success",[date,Max])
        break

The current result will save date and Max value in the same cells.当前结果将在同一单元格中保存日期和最大值。 I want the result to have the header and will be save like this:我希望结果具有标题,并将像这样保存:

Colum A             Column B
Date_time           Max_value
03/01/2019            5.0
04/01/2019            6.0
05/01/2019            7.0
......               .... 

How can I do it?我该怎么做?

CSVs consist of (as the name suggests) comma separated values -- which means you need to make sure that you enter a new row in the correct format. CSV 由(顾名思义)逗号分隔值组成——这意味着您需要确保以正确的格式输入新行。 The decisive line in your code is the following:代码中的决定性行如下:

writer = csv.writer(file, delimiter='\t')

With the delimiter set to \\t you actually get lines separated by tabs.将定界符设置为\\t您实际上会得到由制表符分隔的行。 My suspicion is you're expecting a comma separated line, ie the following change should hopefully make it work:我怀疑您期望使用逗号分隔的行,即以下更改有望使其工作:

writer = csv.writer(file, delimiter=',')

As delimiter=',' is indeed the default value, you can achieve the same result my leaving out the delimiter attribute from the function statement.由于delimiter=','确实是默认值,您可以实现相同的结果,我从函数语句中省略 delimiter 属性。

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

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