I am trying to read a bunch of data in .csv file into an array in format:
[ [a,b,c,d], [e,f,g,h], …]
Running the code below, when I print an entry with a space (‘ ‘) the way I’m accessing the element isn’t correct because it stops at the first space (‘ ‘).
For example if Business, Fast Company, Youtube, fastcompany is the 10th entry…when I print the below I get on separate lines:
Business,Fast
Company,YouTube,FastCompany
Any advice on how to get as the result: [ [a,b,c,d], [Business, Fast Company, Youtube, fastcompany], [e,f,g,h], …]?
import csv
partners = []
partner_dict = {}
i=9
with open('partners.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
partners.append(row)
print len(partners)
for entry in partners[i]:
print entry
The
delimiterargument specifies which character to use to split each row of the file into separate values. Since you’re passing ‘ ‘ (a space), the reader is splitting on spaces.If this is really a comma-separated file, use ‘,’ as the delimiter (or just leave the
delimiterargument out and it will default to ‘,’).Also, the pipe character is an unusual value for the quote character. Is it really true that your input file contains pipes in place of quotes? The sample data you supplied contains neither pipes nor quotes.