create a list of tuples from csv file

早过忘川 提交于 2021-02-04 16:16:19

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/15616139/create-a-list-of-tuples-from-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!