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

我不认为我需要内置csv模块,因为在我看到的所有例子中,它接受文件路径,而不是字符串。


当前回答

不是通用的CSV解析器,但可用于带逗号的简单字符串。

>>> a = "1,2"
>>> a
'1,2'
>>> b = a.split(",")
>>> b
['1', '2']

解析CSV文件。

f = open(file.csv, "r")
lines = f.read().split("\n") # "\r\n" if needed

for line in lines:
    if line != "": # add other needed checks to skip titles
        cols = line.split(",")
        print cols

其他回答

csv.reader() https://docs.python.org/2/library/csv.html的官方文档非常有用,它说

文件对象和列表对象都是合适的

import csv

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

lines = text.splitlines()
reader = csv.reader(lines, delimiter=',')
for row in reader:
    print('\t'.join(row))

对于任何仍然在寻找将标准CSV str转换为列表[str]以及反向的可靠方法的人来说,这里有两个函数,我从这个和其他SO线程中的一些答案组合在一起:

def to_line(row: list[str]) -> str:
    with StringIO() as line:
        csv.writer(line).writerow(row)
        return line.getvalue().strip()


def from_line(line: str) -> list[str]:
    return next(csv.reader([line]))

简单- csv模块也适用于列表:

>>> a=["1,2,3","4,5,6"]  # or a = "1,2,3\n4,5,6".split('\n')
>>> import csv
>>> x = csv.reader(a)
>>> list(x)
[['1', '2', '3'], ['4', '5', '6']]

根据文档:

虽然该模块不直接支持解析字符串,但可以轻松完成:

import csv
for row in csv.reader(['one,two,three']):
    print row

只需将字符串转换为单个元素列表。

当这个例子显式地出现在文档中时,导入StringIO对我来说似乎有点过分。

不是通用的CSV解析器,但可用于带逗号的简单字符串。

>>> a = "1,2"
>>> a
'1,2'
>>> b = a.split(",")
>>> b
['1', '2']

解析CSV文件。

f = open(file.csv, "r")
lines = f.read().split("\n") # "\r\n" if needed

for line in lines:
    if line != "": # add other needed checks to skip titles
        cols = line.split(",")
        print cols