Proper way to reset csv.reader for multiple iterations?

后端 未结 3 2223
情话喂你
情话喂你 2021-02-20 07:47

Having an issue with a custom iterator in that it will only iterate over the file once. I am calling seek(0) on the relevant file object in between iterations, but

3条回答
  •  死守一世寂寞
    2021-02-20 08:34

    For DictReader:

    f = open(filename, "rb")
    d = csv.DictReader(f, delimiter=",")
    
    f.seek(0)
    d.__init__(f, delimiter=",")
    

    For DictWriter:

    f = open(filename, "rb+")
    d = csv.DictWriter(f, fieldnames=fields, delimiter=",")
    
    f.seek(0)
    f.truncate(0)
    d.__init__(f, fieldnames=fields, delimiter=",")
    d.writeheader()
    f.flush()
    

提交回复
热议问题