如何从文件中打印选定的元素?

时间:2015-05-17 15:54:33

标签: python file

我写了一个代码,用于打印文件中的数字:

data=open("fk.txt",'r')
for i in data:
    print i

我得到了这个:

fk id

5 4

4 4

1 2

11 13

10 17

18 17

5 8

我想更改此代码,它只打印高于示例6的元素。我不知道如何将这两个列分成两列。

2 个答案:

答案 0 :(得分:4)

with open("fk.txt") as f:
    next(f) # skip header
    for line in f:
        if line.strip(): # catch empty lines
            a, b = map(int,line.split()) # cast to int
            if a > 6:
                print(a)
            if b > 6:
                print(b)

您接受的答案不会检查数字是否更大,如果您想要两个完整的数字列而不管值是否可以使用zip来转置子列表:

with open("fk.txt") as f:
    next(f) # skip header
    col1, col2 = zip(*(map(int,line.split()) for line in f if line.strip()))
    print(col1,col2)
(5, 4, 1, 11, 10, 18, 5) (4, 4, 2, 13, 17, 17, 8)

通常你应该使用try / except但是如果标题后面只有数字那么错误会更合适

答案 1 :(得分:-1)

这是一种方式:

with open("fk.txt") as file:   # Use file to refer to the file object
    data = file.readlines()
column1, column2 = [], []
for line in data:
    try:
        entry1, entry2 = line.split(' ')
        column1.append(int(entry1))
        column2.append(int(entry2))
    except ValueError:
        pass
print column1, column2