Python: Create a list of tuples from file

后端 未结 2 1780
名媛妹妹
名媛妹妹 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:01

    A very straightforward way would be to use the csv module. E.g.:

    import csv
    
    filename = "input.csv"
    
    with open(filename, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:
            print(row)
    
    0 讨论(0)
  • 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')]
    
    0 讨论(0)
提交回复
热议问题