python 读取文本文件、按空格切割、和第一列组成字典_如何读取由'\x01'分隔的CSV文件,并在python中创建一个字典...

I have a requirement to read a CSV file which is \x01 (^A) delimited and create a dictionary for my lookup for processing my business logic further.

My input file contains many columns, i need to make 14 column as the key and rest as values.

Earlier the file was comma delimited and i was able to read the file and create the dictionary. know the file is coming to me as \x01 delimited and my script is failing

this is how i created dictionary earlier

lake_dataset = csv.DictReader(open(local_registry_file_path+os.path.basename(registryPath),'rb'))

master_dir = {}

for row in lake_dataset:

key = row.pop('TBL_DATASETLOCATION')

key = key.lower().strip()

master_dir[key] = row

解决方案

You can register a custom dialect that uses that character as a separator as seen in this answer.

import csv

class custom_sep(csv.excel):

delimiter = chr(0x01)

csv.register_dialect("custom_sep", custom_sep)

data = """col1\x01col2\x01col3

foo\x01bar\x01baz

moo\x01mee\x01mah"""

data = csv.DictReader((x.strip() for x in data.split('\n')), dialect="custom_sep")

for row in data:

print row

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值