python delimiter分隔符用法_Python:使用多分割分隔符分割文件

1586010002-jmsa.png

I have multiple CSV files which I need to parse in a loop to gather information.

The problem is that while they are the same format, some are delimited by '\t' and others by ','.

After this, I want to remove the double-quote from around the string.

Can python split via multiple possible delimiters?

At the minute, I can split the line with one by using:

f = open(filename, "r")

fields = f.readlines()

for fs in fields:

sf = fs.split('\t')

tf = [fi.strip ('"') for fi in sf]

Any suggestions are welcome.

解决方案

Splitting the file like that is not a good idea: It will fail if there is a comma within one of the fields. For example (for a tab-delimited file): The line "field1"\t"Hello, world"\t"field3" will be split into 4 fields instead of 3.

Instead, you should use the csv module. It contains the helpful Sniffer class which can detect which delimiters are used in the file. The csv module will also remove the double-quotes for you.

import csv

csvfile = open("example.csv")

dialect = csv.Sniffer().sniff(csvfile.read(1024))

csvfile.seek(0)

reader = csv.reader(csvfile, dialect)

for line in reader:

#process line

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值