kate88
kate88

Reputation: 371

create a list of tuples from csv file

I am python beginner struggling to create and save a list containing tuples from csv file in python.

The code I got for now is:

def load_file(filename):
    fp = open(filename, 'Ur')
    data_list = []
    for line in fp:
        data_list.append(line.strip().split(','))
    fp.close()
    return data_list

and then I would like to save the file

def save_file(filename, data_list):
    fp = open(filename, 'w')
    for line in data_list:
        fp.write(','.join(line) + '\n')
    fp.close()

Unfortunately, my code returns a list of lists, not a list of tuples... Is there a way to create one list containing multiple tuples without using csv module?

Upvotes: 3

Views: 9460

Answers (3)

Thorsten Kranz
Thorsten Kranz

Reputation: 12755

First question: why is a list of lists bad? In the sense of "duck-typing", this should be fine, so maybe you think about it again.

If you really need a list of tuples - only small changes are needed.

Change the line

        data_list.append(line.strip().split(','))

to

        data_list.append(tuple(line.strip().split(',')))

That's it.

If you ever want to get rid of custom code (less code is better code), you could stick to the csv-module. I'd strongly recommend using as many library methods as possible.

To show-off some advanced Python features: your load_file-method could also look like:

def load_file(filename):
    with open(filename, 'Ur') as fp:
        data_list = [tuple(line.strip().split(",") for line in fp]

I use a list comprehension here, it's very concise and easy to understand.

Additionally, I use the with-statement, which will close your file pointer, even if an exception occurred within your code. Please always use with when working with external resources, like files.

Upvotes: 7

Giles Thomas
Giles Thomas

Reputation: 5867

Just wrap "tuple()" around the line.strip().split(',') and you'll get a list of tuples. You can see it in action in this runnable gist.

Upvotes: 1

Pavel Anossov
Pavel Anossov

Reputation: 62908

split returns a list, if you want a tuple, convert it to a tuple:

    data_list.append(tuple(line.strip().split(',')))

Please use the csv module.

Upvotes: 8

Related Questions