有人知道一个简单的库或函数来解析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解析器,但可用于带逗号的简单字符串。

>>> 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

根据文档:

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

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

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

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

使用此命令将csv文件加载到列表中

import csv

csvfile = open(myfile, 'r')
reader = csv.reader(csvfile, delimiter='\t')
my_list = list(reader)
print my_list
>>>[['1st_line', '0'],
    ['2nd_line', '0']]

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))

正如其他人已经指出的,Python包含一个模块来读写CSV文件。只要输入字符保持在ASCII限制范围内,它就能很好地工作。如果要处理其他编码,则需要做更多的工作。

csv模块的Python文档实现了csv的扩展。Reader,它使用相同的接口,但可以处理其他编码并返回unicode字符串。只需从文档中复制并粘贴代码。在此之后,您可以像这样处理CSV文件:

with open("some.csv", "rb") as csvFile: 
    for row in UnicodeReader(csvFile, encoding="iso-8859-15"):
        print row