【问题标题】:Splitting string by comma in python在python中用逗号分割字符串
【发布时间】:2015-05-31 06:49:14
【问题描述】:

我有一个包含

的 csv 文件
"VANS, PASSENGER TYPE",CHEVROLET,H1500 EXPRESS AWD,5.3,8,Auto(L4),4,832,9,12,10,11.5,16.2,13.2268,E,,,,,,,,,,3900,310-340,CLKUP ,2,15,30-Jun-07,DERIVED

我要做的只是用逗号分隔,我目前的解决方案唯一的问题是第一个条目恰好是 "VANS, PASSENGER TYPE" 有一个逗号,但我对拆分它不感兴趣。

目前我正在做这样的事情

with open("file.txt", "r") as ins:
   foo = ins.split(",")

【问题讨论】:

  • 如果您有 CSV 文件,为什么不使用 csv 模块?
  • 不知道那个模块......看起来很有趣......让我试试看!

标签: python regex csv readfile


【解决方案1】:

最好使用csv module

import csv
with open('file') as f:
    reader = csv.reader(f)
    for line in reader:
        print(line)

输出:

['VANS, PASSENGER TYPE', 'CHEVROLET', 'H1500 EXPRESS AWD', '5.3', '8', 'Auto(L4)', '4', '832', '9', '12', '10', '11.5', '16.2', '13.2268', 'E', '', '', '', '', '', '', '', '', '', '3900', '310-340', 'CLKUP ', '2', '15', '30-Jun-07', 'DERIVED']

【讨论】:

    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 2018-05-20
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多