簡體   English   中英

僅打印.csv文件中的最后8個條目

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

我有一個輸入的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

您可以將尾部配方與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']
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

如果內存/性能不是問題,則可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM