Paulo19
Paulo19

Reputation: 45

Strange results when using ForLoop to read CSV and add data to list

I have some code that reads data in a csv file and stores it in a list. Later in the program I edit this list and add new data to it.

fileData = []
with open('translation list.csv', 'r') as rFile:
    fileReader = csv.reader(rFile)

    for row in fileReader:
    fileData.append(row)

The last line of this code seems to be causing problems.

Now every line that gets read is wrapped in [ ] and I can't figure out why. So I end up with a csv that looks like this:

[[[list item 4]]]

[[list item 3]]

[list item 2]

list item 1

Upvotes: 1

Views: 31

Answers (1)

elethan
elethan

Reputation: 16993

When you use += with lists a and b (a += b), it will add all individual items from b to the end of a. When you use a.append(b), it adds the entire list b to the end of a. Observe:

In [1]: a = [1, 2, 3]

In [2]: b = ['a', 'b', 'c']

In [3]: a.append(b)

In [4]: a
Out[4]: [1, 2, 3, ['a', 'b', 'c']]

Compared to:

In [1]: a = [1, 2, 3]

In [2]: b = ['a', 'b', 'c']

In [3]: a += b

In [4]: a
Out[4]: [1, 2, 3, 'a', 'b', 'c']

Each row in for row in fileReader is a list itself, so when you append that list to an existing list, you get a list of lists, rather than single flat list of items in each list.

Upvotes: 1

Related Questions