-4

I have a text file formatted as follows

a,b,c,d,e,f,
g,h,i,j,k,l,

How would I read this and store it as an array that looks like [[a,b,c,d,e,f],[g,h,i,j,k,l]]?

A. Khan
  • 1
  • 1

2 Answers2

2

When reading comma separated values from a file, it is easiest to use Python's CSV library, for example:

import csv

with open('input.csv', 'rb') as f_input:
    data = list(csv.reader(f_input))

print data

This also then copes with the case when the entries contain a comma (and is enclosed in quotes). For example this should contain 6 cells:

a,b,c,"d,e,f",h,i
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
1
with open('yourfile.txt') as f:
    lines = [line.strip().split(',') for line in f]
joppich
  • 681
  • 9
  • 20