仅打印所需的列

时间:2018-08-30 17:19:14

标签: python python-3.x csv

我只想在打印时显示所需的列。原始数据如下所示。

  

['* 10 6cb2.aeee.0db7动态300 F F Po11']

我要打印“ 10” ,“ 6cb2.aeee.0db7 ”和“ Po11 ”。

with open('c:/sw_mac_addr/test.txt', newline='') as f:
    reader = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(row)

2 个答案:

答案 0 :(得分:2)

您可以使用operator.itemgetter并通过列表提供列索引。这也适用于负数索引:

from io import StringIO
import csv
from operator import itemgetter

x = StringIO("""*\t10\t6cb2.aeee.0db7\tdynamic\t300\tF\tF\tPo11""")
cols = [1, 2, -1]

# replace x with open('file.txt', 'r', newline='')
with x as fin:
    reader = csv.reader(fin, delimiter='\t', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(itemgetter(*cols)(row))

('10', '6cb2.aeee.0db7', 'Po11')

答案 1 :(得分:0)

lines=open("Practice.txt",'r')

for line in lines.readlines():
    tokens=line.split(" ")
print(tokens[1],tokens[2],tokens[-1])