0

I'm trying to create a list in python from a csv file. The CSV file contains only one column, with about 300 rows of data. The list should (ideally) contain a string of the data in each row.

When I execute the below code, I end up with a list of lists (each element is a list, not a string). Is the CSV file I'm using formatted incorrectly, or is there something else I'm missing?

filelist = []                
with open(r'D:\blah\blahblah.csv', 'r') as expenses:
    reader = csv.reader(expenses)
    for row in reader:
        filelist.append(row)
2
  • Show your input and output. Commented May 13, 2013 at 22:20
  • A CSV is a sequence of rows. A row is a sequence of column values. The column values are strings. So, iterating a CSV like this should give you a list of lists of strings. Commented May 13, 2013 at 22:38

3 Answers 3

7

row is a row with one field. You need to get the first item in that row:

filelist.append(row[0])

Or more concisely:

filelist = [row[0] for row in csv.reader(expenses)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this seems to work. It didn't occur to me to stress the specific item within the row, when there is only one item to begin with.
1

It seems your "csv" doesn't contain any seperator like ";" or ",". Because you said it only contains 1 column. So it ain't a real csv and there shouldn't be a seperator.

so you could simply read the file line-wise:

filelist = []
for line in open(r'D:\blah\blahblah.csv', 'r').readlines():
    filelist.append(line.strip())

2 Comments

Not a good idea because of escaped separators and quotes and other csv typical signs...
Yes COULD be. Depends on the input file and if it is a rfc-compliant csv or just plain text file.
0

Each row is read as list of cells. So what you want to do is

output = [ row[0] for row in reader ]

since you only have the first cell filled out in each row.

1 Comment

So slow when typing on my cellphone -.-*

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.