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