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

查看:42
本文介绍了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.

推荐答案

您可以使用 io.StringIO 然后将其传递给 csv 模块:

from io import StringIO
import csv

scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""

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

在换行符上使用 split() 的简单版本:

simpler version with split() on newlines:

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

或者你可以简单地将这个字符串split()使用\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 2 上,您必须将 StringIO 导入为

On Python 2 you have to import StringIO as

from StringIO import StringIO

相反.

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

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