简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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