Home > Net >  how to read a csv file edited from excel in python?
how to read a csv file edited from excel in python?

Time:05-16

Hi I tried loading the csv file that has been edited and saved as csv comma delimited. However it's not loading right.

I used the normal pd_read_csv like so.

df = pd.read_csv('file.csv',quotechar'"')

However the file returns back as so:

productId items unit
1 orange juice 3 300ml
2,"lime juice 3,4","300ml"
3 grape juice 2 300ml

When I tried opening the file in text it returns as so

productId,items,unit
1,orange juice 3,300ml
2,""lime juice 3,4"",300ml
3,grape juice 2, 300ml

What format is the above csv? Where there's no , after each item and using double quotes? How do I read the csv file?

CodePudding user response:

I don't know how you got to that file, but it looks broken.

productId,items,unit
1,orange juice 3,300ml
2,""lime juice 3,4"",300ml
3,grape juice 2, 300ml

If double quotes are your delimiter ("), then you should have a single one around your quoted fields.

productId,items,unit
1,orange juice 3,300ml
2,"lime juice 3,4",300ml
3,grape juice 2, 300ml

Which pandas can load just fine.

from io import BytesIO

import pandas as pd

dat = BytesIO(b"""\
productId,items,unit
1,orange juice 3,300ml
2,"lime juice 3,4",300ml
3,grape juice 2, 300ml
""")

pd.read_csv(dat) # and you don't need the quotechar kwarg
  • Related