2

I'm trying to make a list from an import file but can't get it to work properly.

import csv

fileName = "/home/bluebird/Desktop/Deck"
# the file is this
# A,A,@,@,$,$,&,&,!,!,H,H,Z,Z,W,W

f = open(fileName, 'r')
reader = csv.reader(f)
allRows = [row for row in reader]

print(allRows)
size = len(allRows)
print(size)

The result I get is:

[['A', 'A', '@', '@', '$', '$', '&', '&', '!', '!', 'H', 'H','Z', 'Z', 'W', 'W']]
1

But I'm trying to get:

['A', 'A', '@', '@', '$', '$', '&', '&', '!', '!', 'H', 'H', 'Z', 'Z', 'W', 'W']
16
3
  • Does allRows = [row for row in reader][0] work? Commented Oct 31, 2017 at 20:46
  • 1
    I was just about to say, it looks like you have a list in a list Commented Oct 31, 2017 at 20:47
  • If you want me to explain it in more detail, just let me know Commented Oct 31, 2017 at 20:52

2 Answers 2

2

The line:

reader = csv.reader(f)

will read in the file and return a reader object. Instead of using a list-comprehension to convert it to a list of each row of data, you can just pass it into list() which is more Pythonic:

allRows = list(reader)

Now, allRows is a list of lists (rows).

As you only have one row in your file, allRows in this case is:

[['A', 'A', '@', '@', '$', '$', '&', '&', '!', '!', 'H', 'H', 'Z', 'Z', 'W', 'W']]

And the length of allRows (len(allRows)) is going to be 1- as there is just one row in the list.

If you want to extract the first row, you can take the first element (row) from the list with:

firstRow = allRows[0]

then if you do:

print(firstRow)

you will get:

['A', 'A', '@', '@', '$', '$', '&', '&', '!', '!', 'H', 'H', 'Z', 'Z', 'W', 'W']

and:

print(len(firstRow))

will give you:

16

As you want :)

Sign up to request clarification or add additional context in comments.

Comments

1

It seems like you have a list in a list.

A quick fix would be

allRows = allRows[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.