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
相反.