Python import csv to list

后端 未结 13 1115
后悔当初
后悔当初 2020-11-22 06:15

I have a CSV file with about 2000 records.

Each record has a string, and a category to it:

This is the firs         


        
13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 06:49

    As said already in the comments you can use the csv library in python. csv means comma separated values which seems exactly your case: a label and a value separated by a comma.

    Being a category and value type I would rather use a dictionary type instead of a list of tuples.

    Anyway in the code below I show both ways: d is the dictionary and l is the list of tuples.

    import csv
    
    file_name = "test.txt"
    try:
        csvfile = open(file_name, 'rt')
    except:
        print("File not found")
    csvReader = csv.reader(csvfile, delimiter=",")
    d = dict()
    l =  list()
    for row in csvReader:
        d[row[1]] = row[0]
        l.append((row[0], row[1]))
    print(d)
    print(l)
    

提交回复
热议问题