2013-06-27 53 views
1

我有一個如下所示的輸入csv文件,我只想打印最近的8個條目..任何人都可以提供有關如何執行此操作的輸入信息?僅打印.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 
+0

你嘗試存儲8項? –

+0

@ IgnacioVazquez-Abrams - 我只想存儲8個條目..bot確定如何做到這一點雖然..任何輸入? – user2341103

+0

@ IgnacioVazquez-Abrams - 我得到一個錯誤文件「database.py」,第17行,在 last8 = collections.deque(maxlength = 8) TypeError:'maxlength'是這個函數的無效關鍵字參數 – user2341103

回答

4

你可以用一個具有n個雙端隊列使用tail recipe = 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'] 
+0

我得到錯誤NameError:名稱'reader'未定義 – user2341103

+0

您是否完全使用此代碼? 'reader'是上面定義的csv對象。這是你的代碼中的'cr'... – dawg

+0

+1不錯!但是使用''rb''作爲'open'並帶有'csv'(或Python 3中的'newline =''')。 –

0

如果內存/性能不是你可以只是做一個問題:

for row in list(cr)[-8:]: 
    print row 
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 
相關問題