【问题标题】:Error when reading columns in txt file with python使用python读取txt文件中的列时出错
【发布时间】:2021-03-08 01:05:15
【问题描述】:

我有一个 1150 行 5 列的 txt 文件。列用制表符分隔。 我想获取包含 txt 文件的某一列的数组。我使用以下代码来获取列:

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

有了这个我得到了我第一列的所有值,但是当我想得到第二列时

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

我得到一个 IndexError: 列表索引超出范围

我该如何解决这个问题?

【问题讨论】:

  • 调试打印x看是否真的有5个字段
  • 它似乎有 5 个字段。前 3 行的输出为: 0001 0 0001.PNG 0 0 0002 0 0002.PNG 0 0 0003 0 0003.PNG 0 0

标签: python readfile indexoutofrangeexception txt


【解决方案1】:

尝试在循环中打印每个 x 的长度:

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

【讨论】:

  • 谢谢!我发现了错误,我的 txt 文件以只有 1 列的行开头...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多