Why do I get alternative empty lists in the csv file

Viewed 41

the output I am getting has empty lists at alternate positions, I do not know why? can someone tell me

    from pathlib import Path
    import csv
    daily_temperatures = [
     [68, 65, 68, 70, 74, 72],
     [67, 67, 70, 72, 72, 70],
     [68, 70, 74, 76, 74, 73],
    ]
    file = Path.home()/"temper.csv"
    with open(file, mode = "w", encoding = "utf-8") as file:
        writer = csv.writer(file)
    
        for temp_list in daily_temperatures:
            writer.writerow(temp_list)
    
    file = Path.home()/"temper.csv"
    all_temps=[]
    with open(file, mode = "r", encoding = "utf-8") as file:
        reader = csv.reader(file)
    
    for row  in reader:
        daily_temp = [int(x) for x in row]
        all_temps.append(daily_temp)
    
all_temps
1 Answers

The code is correct but within the with open() you need to provide newline argument

with open(file, mode = "w", encoding = "utf-8", newline='') as file:
    writer = csv.writer(file)    
    for temp_list in daily_temperatures:
        print(temp_list)
        writer.writerow(temp_list) 

https://docs.python.org/3/library/csv.html#footnote-1

Related