reading csv file without for

前端 未结 8 1692
孤街浪徒
孤街浪徒 2020-12-10 04:28

I need to read a CSV file in python.

Since for last row I receive a \'NULL byte\' error I would like to avoid using for keyword but the while.

Do you know ho

8条回答
  •  感情败类
    2020-12-10 05:09

    Maybe you could catch the exception raised by the CSV reader. Something like this:

    filename = "my.csv"
    reader = csv.reader(open(filename))
    try:
        for row in reader:
            print 'Row read with success!', row
    except csv.Error, e:
        sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
    

    Or you could use next():

    while True:
        try: 
            print reader.next()
        except csv.Error:
            print "Error"
        except StopIteration:
            print "Iteration End"
            break
    

提交回复
热议问题