2013-12-21 43 views
0

柱閱讀CSV我有即有空白的空白行或隨機的新線路,如下面問題在python

header1,data1 
header2,data2 

header4,data4 

header6,data6 

的例子一個CSV文件下下面的示例工作正常時,CSV沒有空白空間,但有沒有辦法用空白欄加載CSV?

import csv 

file = csv.reader(open('file.csv')) 
blob = zip(*file) 
+0

它產生的錯誤是什麼? –

+0

@bludger這個blob會成爲'[]' – pyCthon

回答

1

我過濾行之前的zip [蟒2假定爲open]:

>>> import csv 
>>> with open("blank.csv", "rb") as fp: 
...  reader = csv.reader(fp) 
...  rows = [line for line in reader if line] 
...  blob = zip(*rows) 
...  
>>> blob 
[('header1', 'header2', 'header4', 'header6'), ('data1', 'data2', 'data4', 'data6')] 

if line這裏基本上等同於if len(line) > 0

1

大熊貓將工作:

import pandas 
pandas.read_csv("tmp.txt", header=None) 

     0  1 
0 header1 data1 
1 header2 data2 
2  NaN NaN 
3 header4 data4 
4  NaN NaN 
5 header6 data6 

你可能要篩選出的NaN。

+0

熊貓是非常好的,但有沒有純粹的Python方式待辦事項呢? – pyCthon