Python: Create a list of tuples from file

后端 未结 2 1851
名媛妹妹
名媛妹妹 2021-01-17 05:57

I have a test file that I would like to load the create a list of tuples using the data on the file. The data on the file is as follows> how would I successfully load the fi

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 06:16

    Use the csv module to parse the file:

    import csv
    
    output = []
    with open('input_file') as in_file:
        csv_reader = csv.reader(in_file)
        for row in csv_reader:
            output.append(tuple(row))
    
    print output
    

    This returns a list of tuples, each tuple corresponding to every line in the input file.

    [('ocean', '4'), ('-500', ' -360'), ('-500', ' 360'), ('500', ' 360'), ('500', '-360')]
    

提交回复
热议问题