仅打印.csv文件中的最后8个条目

时间:2013-06-27 03:31:12

标签: python csv

我有一个输入csv文件,如下所示,我想只打印最近的8个条目..任何人都可以提供有关如何执行此操作的输入吗?

INPUT:-
trend.csv

['2013-06-25 20:01', '10']
['2013-06-25 20:06', '9']
['2013-06-25 20:06', '8']
['2013-06-26 20:06', '7']
['2013-06-26 20:06', '6']
['2013-06-26 20:06', '5']
['2013-06-26 20:06', '4']
['2013-06-26 20:06', '3']
['2013-06-26 20:06', '2']
['2013-06-26 20:08', '1']

OUTPUT:-
['2013-06-25 20:06', '8']
['2013-06-26 20:06', '7']
['2013-06-26 20:06', '6']
['2013-06-26 20:06', '5']
['2013-06-26 20:06', '4']
['2013-06-26 20:06', '3']
['2013-06-26 20:06', '2']
['2013-06-26 20:08', '1']

代码:

import csv
#Now read the recent 8 entries and print
cr = csv.reader(open("trend.csv","rb"))

for row in cr:  
    #print only the recent most 8 entries
    print row

3 个答案:

答案 0 :(得分:4)

您可以将tail recipe与带有n = 8的双端队列一起使用。

这会创建一个双端队列,其中向末尾添加项目(右)将有效弹出开头(左侧)的项目以保持长度不超过最大长度:

>>> from collections import deque
>>> deque(range(10000),8)
deque([9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999], maxlen=8)

csv.reader对象是一个迭代器。在csv阅读器上应用一个有限长度的双端队列,你可以去:

import csv
from collections import deque

with open('/tmp/trend.csv','rb') as fin:
    deq=deque(csv.reader(fin),8)

for sub_list in deq:
    print sub_list

使用10行示例,打印:

['2013-06-25 20:06', '8']
['2013-06-26 20:06', '7']
['2013-06-26 20:06', '6']
['2013-06-26 20:06', '5']
['2013-06-26 20:06', '4']
['2013-06-26 20:06', '3']
['2013-06-26 20:06', '2']
['2013-06-26 20:08', '1']

答案 1 :(得分:1)

import csv

# Open the file with a "with" statement to provide automatic cleanup
# in case of exceptions.
with open("trend.csv","rb") as file:
    cr = csv.reader(file)
    lines = [row for row in cr]
# Use slice notation and the wonderful fact that python treats
# negative indices intelligently!
for line in lines[-8:]:
    print line

答案 2 :(得分:0)

如果内存/性能不是问题,你可以这样做:

for row in list(cr)[-8:]:  
    print row