PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] Why I'm Having empty rows when appending?

 August 28, 2022     csv, dataframe, pandas, python     No comments   

Issue

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?


Solution

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)


Answered By - Michel Kok
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing