读取csv文件而没有 [英] reading csv file without for

查看:311
本文介绍了读取csv文件而没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在python中读取一个CSV文件。

I need to read a CSV file in python.

由于最后一行我收到一个NULL字节错误,我想避免使用for关键字,但

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

你知道如何做吗?


    reader = csv.reader( file )
    for row in reader  # I have an error at this line
          # do whatever with row

我想用while循环替换for循环,以便我可以检查该行是否为NULL。

I want to substitute the for-loop with a while-loop so that I can check if the row is NULL or not.

读取单行在CSV模块中?
感谢

What is the function for reading a single row in the CSV module? Thanks

感谢


Traceback (most recent call last):
  File "FetchNeuro_TodayTrades.py", line 189, in 
    for row in reader:
_csv.Error: line contains NULL byte


推荐答案

也许你可以抓住CSV读者提出的异常。像这样:

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))

或者,您可以使用 next()

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

这篇关于读取csv文件而没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆