Python: How to import information from a .csv file to python as a list with tuples inside?

后端 未结 2 1188
自闭症患者
自闭症患者 2021-01-22 17:16

I am new to programming so please excuse my shallow knowledge with coding. I have a .csv file that I can open with excel. Each row represents a person\'s name and their details

相关标签:
2条回答
  • 2021-01-22 17:40

    With the csv module it is quite simple:

    import csv
    
    with open('friends.csv', 'Ur') as f:
        data = list(tuple(rec) for rec in csv.reader(f, delimiter=','))
    

    data is a list of tuples.

    The csv module reads the files correctly:

    "Smith, John",123
    

    will be read as

    ('Smith, John', '123')
    
    0 讨论(0)
  • 2021-01-22 17:48
    import csv
    DIR = 'your dicrectory path'
    openfile = csv.DictReader(open(DIR + '/file_name.csv', 'r'))
    print .fieldnames
    for p in filename:
        try:
            p = dict((k.strip().strip('\\t'), v) for k, v in p.iteritems() if v.lower() != 'null')
    except AttributeError, e:
        print e
        print p
        raise Exception()
    print p.get('Name'),p.get('Details')
    
    0 讨论(0)
提交回复
热议问题