【问题标题】:Python: loop through a file for specific linesPython:循环遍历特定行的文件
【发布时间】:2010-10-12 20:32:57
【问题描述】:

我在一个文件中有以下行,我想在其中获取第三列;在文件中我没有数字列:

  1. 红色;蓝色的;绿色的;白色的;橙色;
  2. 绿色;白色的;橙色;
  3. 蓝色;绿色的;白色;
  4. 红色;蓝色的;绿色的;白色;
  5. 蓝色;绿色的;白色的;橙色;
  6. 橙色
  7. 绿色;白色的;橙色;
  8. 白色;橙色
  9. 绿色;

我使用此代码行来做到这一点:

lines = i.split(";")[2]

问题是有些行只有一两列,所以它给了我“索引超出范围”的错误。请告诉我如何解决这个问题?

非常感谢 阿迪亚

【问题讨论】:

  • 嗯,列数不够怎么办?

标签: python


【解决方案1】:

这样的事情怎么样:

cols = i.split(";")
if (len(cols) >= 3):
    lines = cols[2]
else:
    #whatever you want here

【讨论】:

    【解决方案2】:

    简单的解决方案是检查列数并忽略少于三列的行。

    third_columns = []
    with open("...") as infile:
        for line in infile:
            columns = line.split(';')
            if len(columns) >= 3:
                third_columns.append(columns[2])
    

    如果您解析 CSV(看起来像这样),您最好使用众多现有的 CSV 解析器之一,e.g. the one in the standard library

    【讨论】:

      【解决方案3】:

      使用切片而不是索引。

      >>> with open('test.txt') as f_in:
      ...     column3 = (line.split(';')[2:3] for line in f_in)
      ...     column3 = [item[0] for item in column3 if item]
      ... 
      >>> column3
      [' Green', ' Orange', ' White', ' Green', ' White', ' Orange']
      

      【讨论】:

        【解决方案4】:
        for line in open("file"):
            try:
                s=line.split(";")[2]
            except: pass
            else:
                print s
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-05
          • 1970-01-01
          相关资源
          最近更新 更多