pgblu
pgblu

Reputation: 702

why is csv reader creating a nested list?

Started learning python after lots of ruby experience. With that context in mind:

I have a csv file that looks something like this:

city_names.csv

"abidjan","addis_ababa","adelaide","ahmedabad"

With the following python script I'd like to read this into a list:

city_names_reader.py

import csv

city_name_file = r"./city_names.csv"

with open(city_name_file, 'rb') as file:
  reader = csv.reader(file)
  city_name_list = list(reader)

print city_name_list

The result surprised me: [['abidjan', 'addis_ababa', 'adelaide', 'ahmedabad']]

Any idea why I'm getting a nested list rather than a 4-element list? I must be overlooking something self-evident.

Upvotes: 0

Views: 1377

Answers (3)

ElmoVanKielmo
ElmoVanKielmo

Reputation: 11290

As others suggest, your file is not an idiomatic CSV file. You can simply do:

with open(city_name_file, "rb") as fp:
    city_names_list = fp.read().split(",")

Upvotes: 2

Emil Vikström
Emil Vikström

Reputation: 91942

A CSV file represents a table of data. A table contains both columns and rows, like a spreadsheet. Each line in a CSV file is one row in the table. One row contains multiple columns, separated by ,

When you read a CSV file you get a list of rows. Each row is a list of columns.

If your file have only one row you can easily just read that row from the list:

city_name_list = city_name_list[0]

Usually each column represent some kind of data (think "column of email addresses"). Each row then represent a different object (think "one object per row, each row can have one email address"). You add more objects to the table by adding more rows.

It is not common with wide tables. Wide tables are those that grow by adding more columns instead of rows. In your case you have only one kind of data: city names. So you should have one column ("name"), with one row per city. To get city names from your file you could then read the first element from each row:

city_name_list = [row[0] for row in city_name_list]

In both cases you can flatten the list by using itertools.chain:

city_name_list = itertools.chain(city_name_list)

Upvotes: 3

pgblu
pgblu

Reputation: 702

Based on comments, here is a possible solution:

import csv

city_name_file = r"./city_names.csv"
city_name_list = []

with open(city_name_file, 'rb') as file:
  reader = csv.reader(file)
  for item in reader:
    city_name_list += item

print city_name_list

Upvotes: 0

Related Questions