user8721051
user8721051

Reputation: 29

How to Convert File into a list in Python

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

Upvotes: 2

Views: 517

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20414

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 :)

Upvotes: 2

SPYBUG96
SPYBUG96

Reputation: 1117

It seems like you have a list in a list.

A quick fix would be

allRows = allRows[0]

Upvotes: 1

Related Questions