如何读取由'\x01'分隔的CSV文件,并在python中创建一个字典 [英] How to read a CSV File delimited by '\x01' and create a dictionary in python

查看:5368
本文介绍了如何读取由'\x01'分隔的CSV文件,并在python中创建一个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取分隔的 \x01 (^ A)CSV文件,并为我的查找创建一个字典,以进一步处理我的业务逻辑。
我的输入文件包含许多列,我需要使14列作为键,并保持为值。

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.

早期的文件是逗号分隔的,我是能够读取文件并创建字典。知道文件是以 \x01 分隔,我的脚本失败

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

这是我创建的字典较早

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

这篇关于如何读取由'\x01'分隔的CSV文件,并在python中创建一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆