使用open在Python 3中打印特定字段

时间:2017-09-05 19:01:54

标签: python

我有这段代码:

with open('/home/adiel/log', 'r') as list:
    content = list.read()
    rows = content.split("\n")
    for row in rows:
        infos = row.split(' ')
        print(infos)

这会给我带来这些价值:

['2', '064328796150', 'eni-4bad5a20', '172.18.0.124', '172.18.0.5', '3306', '39064', '6', '14', '4123', '1504618064', '1504618121', 'ACCEPT', 'OK']
['2', '064328796150', 'eni-4bad5a20', '172.18.0.124', '172.18.0.5', '3306', '62717', '6', '16', '5981', '1504618064', '1504618121', 'ACCEPT', 'OK']
['2', '064328796150', 'eni-4bad5a20', '172.18.0.5', '172.18.0.124', '52909', '3306', '6', '37', '7112', '1504618064', '1504618121', 'ACCEPT', 'OK']

我想只获取字段1和4中的值。我怎么能完成它?

3 个答案:

答案 0 :(得分:2)

因为python是0索引的:

row = row.split(' ')
infos = row[0], row[3]

但您也可能需要将infos存储到列表中以便稍后访问

答案 1 :(得分:1)

itemgetter可以提供优雅的解决方案:

from operator import itemgetter
ig = itemgetter(0,3)

with open('/home/adiel/log', 'r') as list:
    content = list.read()
    rows = content.split("\n")
    for row in rows:
        infos = row.split(' ')
        relevant_infos=ig(infos)
        print(relevant_infos)

答案 2 :(得分:0)

您可以使用list comprehension执行以下操作:

with open('/home/adiel/log', 'r') as f:
    print([[x.split()[0], x.split()[3]] for x in f])

或者如果您想分别打印每一行:

with open('/home/adiel/log', 'r') as f:
    for line in [[x.split()[0], x.split()[3]] for x in f]:
        print(line)