Reading CSV rows with a tricky file in Python

时间:2016-02-12 19:47:16

标签: python csv

I've got a little bit of a headache here. I'm new to working to CSVs in Python, but here's what I've got: a CSV, generated by airodump (this is an art project/technology demo in which I'm trying to count the number of BSSIDs in a given area). I'm working in Python 3.4 and trying to read the file in. I had a hiccup with some null values, but I seem to have worked around that (hence the perhaps odd way I open the file).

import csv
print ("nibbler starting")
log_initial = open("test.csv", "rU")
logReader = csv.reader((line.replace('\0',' ') for line in log_initial), delimiter=",")
logData = list(logReader)
row_count1 = sum(1 for row in logData)
row_count2 = sum(1 for row in logReader)
print ('Rows = ' + str(row_count1))
print ('Rows = ' + str(row_count2))
for row in logReader:
        print('Row #'+ str(logReader.line_num)+' '+str(row))

So here's what happens. The first line printed says there are 52 rows (correct!), the second line printed says the are 0 rows (oh no, that's not what I expected).

No surprise then, the for loop delivers nothing. If I replace logReader with logData in the loop, then I get the whole file listed line by line. I'd stick with the data as a list, but that limits what I can do with it.

So somehow the file isn't getting properly processed as a CSV. I'm not really sure what to do about that. Any ideas?

1 个答案:

答案 0 :(得分:0)

logData = list(logReader) 

读取logReader中的所有行。再次读取logReader将不会产生任何行,因为迭代器(读取器对象)已经用尽。

相关问题