Home > Software design >  Why I'm Having empty rows when appending?
Why I'm Having empty rows when appending?

Time:07-22

I wrote code to append info to csv file like the following:

import csv
import pandas as pd
import random
from datetime import date

file_name = r"test.csv"
lst = []

X = input("Your name ")
N = random.random()
D = D = date.today()

lst.append(N)
lst.append(X)
lst.append(D)

with open(file_name, 'a') as f:
    writer = csv.writer(f)
    writer.writerow(lst)

df = pd.read_csv('test.csv')
print(df)

It works fine but when i opened the csv file i found some empty rows like this:

https://ibb.co/Qr7NVQs

how to avoid this problem?

CodePudding user response:

You can better avoid doing manual csv writing when you can do it much easier using pandas.

import csv
import pandas as pd
import random
from datetime import date

file_name = "test.csv"
lst = [random.random(), date.today()]

pd.DataFrame(lst).to_csv(file_name)

df = pd.read_csv(file_name)
print(df)
  • Related