Python csv字符串到数组 [英] Python csv string to array

查看:612
本文介绍了Python csv字符串到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道一个简单的库或函数来解析csv编码的字符串并将其转换为数组或字典?

Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary?

我不认为我想要的在 csv模块中,因为在我看到的所有示例中,都需要文件路径,而不是字符串。

I don't think I want the built in csv module because in all the examples I've seen that takes filepaths, not strings.

推荐答案

我会使用 StringIO

import StringIO
import csv

scsv = """1,2,3
a,b,c
d,e,f"""

f = StringIO.StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
    print '\t'.join(row)

split()在换行符:

reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
    print '\t'.join(row)

或者你可以使用 \\ \\ n 作为分隔符,然后 split 将每行都转换为值,但是这种方式你必须知道引用,所以使用 csv 模块。

Or you can simply split this string into lines using \n as separator, and then split each line into values, but this way you must be aware of quoting, so using csv module is preferred.

这篇关于Python csv字符串到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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