2012-06-01 29 views
2

我有幾個csv文件,其中包含帶換行符的字符串。這些文件在Excel中可以正常打開,但是當我嘗試使用csv.DictReader()讀取文件時,csv.DictReader()似乎將字符串中的每個換行符處理爲新的一行數據,而不是忽略運輸在字符串中斷開。在python中,如何讓csv.DictReader正確處理包含行返回的字符串?

我能做些什麼來獲得第二次測試,就像第一次測試一樣?

#csv contents 
this, is, a, test 
1,2,u'thr\nee',4 
5,6,7,8 

     result = [] 
     text = """this, is, a, test 
1,2,u'three',4 
5,6,7,8""" 
     b = StringIO(text) 
     reader = csv.DictReader(b) 
     for row in reader: 
       result.append(row) 

     self.assertEqual(2,len(result)) 
     expected = [{'this': '1', ' test': '4', ' is': '2', ' a': "u'three'"}, {'this': '5', ' test': '8', ' is': '6', ' a': '7'}] 
     self.assertEqual(expected ,result) 

     #With a /n inside the string. 

     result = [] 
     text = """this, is, a, test 
1,2,u'thr\nee',4 
5,6,7,8""" 
     b = StringIO(text) 
     reader = csv.DictReader(b) 
     for row in reader: 
       result.append(row) 

     self.assertEqual(2,len(result)) 
     #expected = [{'this': '1', ' test': '4', ' is': '2', ' a': "u'thr\nee'"}, {'this': '5', ' test': '8', ' is': '6', ' a': '7'}] 
     #self.assertEqual(expected,result) 

回答

3

假設您的CSV內容是否正確引用,instanciating讀者應該做的時候指定相應的quotechar:

http://docs.python.org/release/2.6.7/library/csv.html#csv.Dialect.quotechar

否則,我假設你有UNIX換行符( '\ n')在你的內容和DOS換行符('\ r \ n')作爲行結束符。從Python 2.6.7開始,文檔提到讀者是硬編碼的,無論您指定哪一個都是線路白蟻,不知道它是否與您的Python版本一樣。如果是的話,你必須手動預處理(可能後處理)你的文件,以確保適當的引用或用其他東西替換單個'\ n',然後在csv解析之後做相反的處理。

+0

還有一個事實,即CSV文件應該以二進制模式打開。我記得最近在使用'csv'模塊時遇到了麻煩。 – JAB

相關問題