【问题标题】:Python - Read second column from filePython - 从文件中读取第二列
【发布时间】:2012-06-20 01:19:15
【问题描述】:

我的输入文件有两列。我正在尝试在第二个 for 循环中打印 inputdata1.txt 的第二列。但是我的代码不起作用。谁能告诉我该怎么办?

【问题讨论】:

  • 您应该显示“不工作”的代码,并更详细地解释“不工作”的含义。
  • 另外,您可能想解释一下 inputdata1.txt 中的列是如何分隔的
  • 如果您处理的是 csv 文件(尽管文件扩展名为 .txt),您可以尝试使用 csv

标签: python for-loop file-io readfile


【解决方案1】:
with open('inputdata1.txt') as inf:
    for line in inf:
        parts = line.split() # split line into parts
        if len(parts) > 1:   # if at least 2 parts/columns
            print parts[1]   # print column 2

这假定列由空格分隔。

函数split()可以指定不同的分隔符。例如,如果列用逗号分隔 , 您将在上面的代码中使用 line.split(',')

注意:使用with 打开文件会在您完成后自动关闭,或者遇到异常

【讨论】:

  • line.strip() 后跟line.split() 是多余的
  • 它不打印列中的所有值,它只打印第一个值
【解决方案2】:

你可以做这样的事情。 Separator 是您的文件用来分隔列的字符,例如制表符或逗号。

for line in open("inputfile.txt"):
    columns = line.split(separator)
    if len(columns) >= 2:
        print columns[1]

【讨论】:

    【解决方案3】:

    快和脏

    如果安装了 AWK:

    # $2 for the second column
    os.system("awk '{print $2}' inputdata1.txt")
    

    使用类

    创建一个类:

    class getCol:
        matrix = []
        def __init__(self, file, delim=" "):
            with open(file, 'rU') as f:
                getCol.matrix =  [filter(None, l.split(delim)) for l in f]
    
        def __getitem__ (self, key):
            column = []
            for row in getCol.matrix:
                try:
                    column.append(row[key])
                except IndexError:
                    # pass
                    column.append("")
            return column
    

    如果inputdata1.txt 看起来像:

    你好世界 世界你好

    你会得到这个:

    print getCol('inputdata1.txt')[1]
    #['lo', 'ld']
    

    补充说明

    • 您可以使用pyawk 获得更多 awk 功能
    • 如果您使用的是 Quick 'n dirty 方法,请使用 subprocess.Popen
    • 您可以更改分隔符getCol('inputdata1.txt', delim=", ")
    • 使用filter 删除空值或取消注释pass

    【讨论】:

      【解决方案4】:
      f = open("file_to_read.txt") # open your file
      
      line = f.readline().strip() # get the first line in line
      
      while line: # while a line exists in the file f
          columns = line.split('separator') # get all the columns
          while columns: # while a column exists in the line
              print columns # print the column
          line = f.readline().strip() # get the next line if it exists
      

      使用此代码,您可以访问每一行的所有列。

      【讨论】:

        猜你喜欢
        • 2019-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-27
        • 2015-12-06
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        相关资源
        最近更新 更多