Creating a list using csv.reader()

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)

Answers


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

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

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.


Need Your Help

Android Messenger Application using services

android web-services broadcastreceiver android-service android-broadcast

I want to implement a simple messenger application for Android devices,I'm working with a web service which contains all the required methods for sending and receiving(by pressing the send button a

NSLog not returning consistent results

iphone objective-c ios xcode

I have an NSLog problem where it wont keep the results the same between loads. Its quite frustrating, but if someone could shed some light that would be really great. I'm trying to call an array fr...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.