Python - 从文件中读取第二列

时间:2012-06-20 01:19:15

标签: python for-loop file-io readfile

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

4 个答案:

答案 0 :(得分: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打开文件会自动将其关闭

答案 1 :(得分:7)

你可以这样做。 Separator是您的文件用于分隔列的字符,例如标签或逗号。

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

答案 2 :(得分:5)

快速肮脏

如果安装了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看起来像:

hel   lo   wor   ld
wor   ld   hel   lo

你会得到这个:

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

附加说明

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

答案 3 :(得分:0)

    // sqlite manage

        Class.forName("org.sqlite.JDBC").newInstance();            
            conn = DriverManager.getConnection("jdbc:sqlite:/"+ myDBpath);
            stmt = conn.createStatement();
    //some calculations
    stmt.close();

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