8

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

4

4 回答 4

12
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时,使用来打开您的文件会自动关闭它

于 2012-06-20T01:23:09.887 回答
8

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

for line in open("inputfile.txt"):
    columns = line.split(separator)
    if len(columns) >= 2:
        print columns[1]
于 2012-06-20T01:22:36.920 回答
5

快'n脏

如果安装了 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
于 2015-04-02T09:30:31.430 回答
0
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

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

于 2015-12-31T11:18:59.057 回答