1. 程式人生 > >Python 讀取 csv 檔案忽略引號中欄位的逗號

Python 讀取 csv 檔案忽略引號中欄位的逗號

如題,使用 Python 處理 csv 檔案,之前是這麼處理的:

str = '飛機,火車,汽車'
rel = str.split(',')
> ['飛機','火車','汽車']

一般情況下是正常的,但是如果在某個文字欄位中帶有逗號,處理就會有問題:

str = “飛機,‘火車,book’,汽車"
rel = str.split(',')
> ['飛機','火車','book','汽車']

解決方法

網路搜尋得知 Python 本身就有處理 csv 的模組,

不要嘗試重新創造,

如果要從CSV檔案中讀取行,請使用Python的 csv 模組。

 import csv 
 with open('some.csv')as f:
 reader = csv.reader(f)
 for row in reader:
 print(row)
 
> cat some.csv 
“114111”,“飛機,火車和汽車”,“50”,“BOOK”
 
> python test.py 
 ['114111','Planes,火車和汽車','50','BOOK']