简体   繁体   中英

Error when reading columns in txt file with python

I have a txt file with 1150 lines and 5 columns. The columns are separated with a tab. I want to get arrays containing a certain column of the txt file. I use the following code to get the columns:

f = open(file, "r")
lines=f.readlines()
result=[]
for x in lines:
    result.append(x.split('\t')[0])
f.close()

With this I get all the values of my first column, but when I want to get the second column with

result.append(x.split('\t')[1])

I get an IndexError: list index out of range

How can I solve this problem?

Try printing the lenght of each x within the loop:

print(len(line.split('\t')))

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