-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]]?

3
  • Are a, b, etc strings here? Commented Feb 1, 2018 at 12:02
  • try splitting by "," and "\n" by my logic that will create a list with 2 lists with the values Commented Feb 1, 2018 at 12:05
  • 2
    Did you even bother searching? There are dozens, if not hundreds, of stack overflow posts about reading csv files. Commented Feb 1, 2018 at 12:07

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1
with open('yourfile.txt') as f:
    lines = [line.strip().split(',') for line in f]

2 Comments

Would this not create an empty element at the end of each inner list?
no, it would create a useless list around the inner list and leave the newline on the last char. edited accordingly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.