Read specific columns in csv using python

前端 未结 7 1383
耶瑟儿~
耶瑟儿~ 2021-02-06 06:27

I have a csv file that look like this:

+-----+-----+-----+-----+-----+-----+-----+-----+
| AAA | bbb | ccc | DDD | eee | FFF | GGG | hhh |
+-----+-----+-----+-----+---         


        
7条回答
  •  别那么骄傲
    2021-02-06 07:12

    import csv
    
    DESIRED_COLUMNS = ('AAA','DDD','FFF','GGG')
    
    f = open("myfile.csv")
    reader = csv.reader(f)
    
    headers = None
    results = []
    for row in reader:
        if not headers:
            headers = []
            for i, col in enumerate(row):
            if col in DESIRED_COLUMNS:
                # Store the index of the cols of interest
                headers.append(i)
    
        else:
            results.append(tuple([row[i] for i in headers]))
    
    print results
    

提交回复
热议问题