-1

So i have been reading answers on StackOverflow and haven't been able to find this specific doubt that i have.

I have a csv with a single column with values as follows:

**Values**
abc
xyz
bcd,fgh
tew,skdh,fsh

As you can see above some cells have more than one value separated by commas, i used the following code:

with open('dat.csv', 'rb') as inputfile:
reader = csv.reader(inputfile)

colnames=['Keywords']
data = pandas.read_csv('dat.csv', names=colnames)   

lkn=data.values.tolist()
print lkn

The output i got was: [['abc'],['xyz'],['bcd,fgh'],['tew,skdh,fsh']] i would like to have the output as:

[['abc'],['xyz'],['bcd','fgh'],['tew','skdh','fsh']]

which i believe is a proper list of list format(fairly new to list of lists). Please do provide guidance in the right direction. Thanks!.

NB:csv file with how cells are arranged (image)

Amal Sailendran
  • 341
  • 1
  • 2
  • 16
  • Is "tew,skdh,fsh" one string? It is usually bad practice to use commas as values in comma separated value files. Also, why is it a CSV at all? If you are trying to learn how to use the csv library then fair enough, however, would simply reading a file work for this? – James Geddes Apr 07 '18 at 09:49

2 Answers2

1

Looking at your attached image, I'd bet that the cells have been quoted (although, to be sure, open the CSV file in a text editor, not in Excel) so you have to do the manual splitting yourself:

import csv

with open("file.csv", "r") as f:
    reader = csv.reader(f)
    your_list = [e[0].strip().split(",") for e in reader if e]
zwer
  • 24,943
  • 3
  • 48
  • 66
0

Try something like this :

import csv

with open('file.csv', 'r') as f:
  reader = csv.reader(f)
  your_list = list(reader)

for item in your_list:
    item = list(item)

print(your_list)

Credit : Python import csv to list

Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34
  • it still gives me the same output..[['abc'],['xyz'],['bcd,fgh'],['tew,skdh,fsh']], i would like to have each element inside [] in ' '. which is: [['abc'],['xyz'],['bcd','fgh'],['tew','skdh','fsh']] – Amal Sailendran Apr 07 '18 at 05:56
  • @AmalSailendran Please check again. The output of this code seems to be : `[['abc'], ['xyz'], ['bcd', 'fgh'], ['tew', 'skdh', 'fsh']] ` – Sruthi Apr 07 '18 at 05:58
  • I tried it again and found the same output. I copy pasted the code and ran it. – Amal Sailendran Apr 07 '18 at 06:04
  • @AmalSailendran - are you sure that the CSV you've posted looks exactly like that? Could the rows be actually within quotes? You can try setting a delimiter to a comma explicitly with `csv.reader(f, delimiter=",")` but that should be the default behavior anyway. – zwer Apr 07 '18 at 06:14