简体   繁体   中英

Reading key value pair from a tab delimited file in python

Following are my contents [ please ignore if its not already tab delimited. I am told it will be]

A B    C 

         1             2              3 

I want to read in such a way that A gets 1, B gets 2, and C gets 3.

Here's my code. I just started to print the first index of each line. But the result I see is the entire file content.

with open('output.txt','rb') as fp:
for x in fp:
    y = x.split('\t')
    print y[0]    

To populate a dictionary, you need a set of keys and a corresponding set of values. Your keys are in the first line and the values are in the second line of your file. So you can do this:

with open('path/to/file') as infile:
    keys = infile.readline().split()
    values = infile.readline().strip().split('\t')

    answer = {}
    for i,key in enumerate(keys):
        answer[key] = values[i]

Of course, the csv module is likely going to help with a lot of the heavy lifting (not that you have much of it in this particular case):

import csv

answer = {}
with open('path/to/file') as infile:
    infile = csv.reader(infile, delimiter='\t')
    keys = next(infile)
    values = next(infile)
    answer.update(dict(zip(keys, values)))

If you are unsure of how the file is delimited, but you know that some form of whitespace is used, then you could simply modify the first solution:

with open('path/to/file') as infile:
    keys = infile.readline().split()
    values = infile.readline().split('\t')

    answer = dict(zip(keys, values))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM