簡體   English   中英

處理python csv模塊中的reader對象的問題

[英]Issue with handling the reader object in python csv module

我要實現的目標是僅從大型csv文件中讀取所需的特定數據。 為此,我有一個主菜單用作數據采集的處理程序,然后有一個單獨的菜單用於退出或繼續。 當我在遍歷文件一次后嘗試讀取更多數據時,就會出現我的問題。 問題是我已經到達文件末尾,由於某種原因,for循環無法正確處理StopIterator錯誤。 有什么建議么? 提前致謝!

fname = open(current_file, 'r')
reader = csv.reader(fname)
for row in reader:
    list_header = row
    break
def main_menu():
    i=0
    menu = {}
    print reader
    for hdr in list_header:
        menu[str(i)]=hdr
        i+=1;
    options=menu.keys() #creates a list out of the keys
    options.sort()
    for entry in options: 
        print entry, menu[entry]
    selection=raw_input("Please Select:") 
    data=[]
    for row in reader:
        a=0
        for block in row:
            if a==list_header.index(menu[selection]):
                data.append(block)
            a+=1
    print 'Saving '+menu[selection]+' values into an array.'+'\n'
    return data

def continue_menu():
    menu_1={}
    menu_1['0']='Continue'
    menu_1['1']='Exit'
    options=menu_1.keys()
    options.sort()
    for entry in options:
        print entry, menu_1[entry]
    selection=raw_input('Please Select:')
    if float(selection)==0:
        print 'As you wish'+'\n'
        proceed=True
    else:
        proceed=False
    return proceed
proceed=True    

while proceed:
    data1=main_menu()
    proceed=continue_menu()

csv.reader從文件對象讀取行,並將其拆分為行。 當您到達文件末尾時,將引發StopIterationfor循環將捕獲該異常,然后循環將停止。 現在,文件指針位於文件的末尾。 如果您嘗試第二次遍歷它,它已經在末尾並立即引發StopIteration 注意在該示例中,第二遍沒有打印任何內容

>>> import csv
>>> fname=open('a.csv')
>>> reader = csv.reader(f)
>>> for row in reader:
...     print(row)
... 
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

>>> for row in reader:
...     print(row)
... 
>>>

一種解決方案是將文件指針回退到文件的開頭。 現在,循環再次起作用

>>> fname.seek(0,0)
0
>>> for row in reader:
...     print(row)
... 
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

另一個更常用的解決方案是在迭代之前打開文件。 通過使用while該文件的使用和運行循環的下一次后立即關閉,該文件被打開,並再次重復。

>>> with open('a.csv') as fname:
...     for row in csv.reader(fname):
...         print(row)
... 
['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

暫無
暫無

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

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