开发者

Continue reading rows in a for loop despite of null values in a row

I am reading csv files in a loop. The problem开发者_如何学JAVA is there are some NUll values inserted in a csv file, and when for loop reads those lines, it generates error.

My code is:

    reader = csv.reader(f, delimiter=';',quotechar = '"')
    data = StringIO.StringIO()
        for line in reader:
            data.write("\"" + str(line[i].encode('UTF-8')) + "\"")
                     .......


and the error is :

for line in reader: _csv.Error: line contains NULL byte

If I use "try and except" , as soon as it gets Null value it enters inside except and does not continue reading other rows in a file. Whereas I want for loop to skip the null values and continue reading other rows in a file.

My sample data is:

"a";"b";"c"
 NulNulNul "f";"v";"x"
 "aaa";"fb";"a"
 "abb";"aab";"aac"

And i want the data after for loop to be,

 "a";"b";"c"
 "f";"v";"x"
 "aaa";"fb";"a"
 "abb";"aab";"aac"


reader = csv.reader( (line.replace('\0','') for line in f) , delimiter=';',quotechar = '"')

this removes the nuls from the lines before csv.reader gets them

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜