简体   繁体   English

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

[英]printing only the last 8 entries in a .csv file

I have an input csv file as below,I want to print only the most recent 8 entries..can anyone provide inputs on how to do this? 我有一个输入的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']

Code: 码:

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

You can use the tail recipe with a deque with n=8. 您可以将尾部配方与n = 8的双端队列配合使用。

This creates a double ended queue where adding an item to the end (right) will efficiently pop off an item at the beginning (the left) to keep the length no more than max length: 这将创建一个双头队列,在该队列中,将一个项目添加到末尾(右侧)将有效地弹出一个项目,使它的开头(左侧)不超过最大长度:

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

The csv.reader object is an iterator. csv.reader对象是一个迭代器。 Apply a limited-length deque to the csv reader and you are good to go: 将有限长度的双端队列应用于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

With your 10 line example, this prints: 以您的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']
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

If memory/performance isn't an issue you could just do: 如果内存/性能不是问题,则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM