0

I am trying to learn python and a beginner. I have a tab delimited text file and I would like to extract 2nd column of the file using the header name of the 2nd column. This is my dummy file:

col1    col2    col3    col4
a   1   2   3
d   4   5   0
f   3   2   1

I have done something like this:

f = open('test.txt',"r")
header = f.readline()
header = firstline.rstrip("\n").split("\t")
for row in f:
 row = row.rstrip("\n")
 # i cannot figure out what should I do next

I want the output to be

col2
1
4
3

1 Answer 1

1

You could store the index of your column in a variable:

f = open("test.txt", "r")
col_index = f.readline().rstrip("\n").split("\t").index("col2")
for row in f:
    print(row.rstrip("\n").split("\t")[col_index])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.