【发布时间】:2015-11-07 15:19:51
【问题描述】:
我第一次遇到将 csv 加载到 Python 中的问题。
我正在尝试做this。我的 csv 文件与他的相同,但更长且值不同。
当我运行它时,
import collections
path='../data/struc.csv'
answer = collections.defaultdict(list)
with open(path, 'r+') as istream:
for line in istream:
line = line.strip()
try:
k, v = line.split(',', 1)
answer[k.strip()].append(v.strip())
except ValueError:
print('Ignoring: malformed line: "{}"'.format(line))
print(answer)
一切运行良好。我得到了你所期望的。
如果没有从link 复制和粘贴代码,在这两种情况下都会出错。
在接受的答案中,终端返回 ValueError: need more than 1 value to unpack
在第二个答案中,我得到 AttributeError: 'file' object has no attribute 'split'。如果您调整它以获取列表,它也不起作用。
我觉得问题出在 csv 文件本身。它的头是
_id,parent,name,\n
Section,none,America's,\n
Section,none,Europe,\n
Section,none,Asia,\n
Section,none,Africa,\n
Country,America's,United States,\n
Country,America's,Argentina,\n
Country,America's,Bahamas,\n
Country,America's,Bolivia,\n
Country,America's,Brazil,\n
Country,America's,Colombia,\n
Country,America's,Canada,\n
Country,America's,Cayman Islands,\n
Country,America's,Chile,\n
Country,America's,Costa Rica,\n
Country,America's,Dominican Republic,\n
我已经阅读了很多关于 csv 的内容,尝试了 import csv 的内容,但仍然没有运气。
请有人帮忙。遇到这种问题是最糟糕的。
import re
from collections import defaultdict
parents=defaultdict(list)
path='../data/struc.csv'
with open(path, 'r+') as istream:
for i, line in enumerate(istream.split(',')):
if i != 0 and line.strip():
id_, parent, name = re.findall(r"[\d\w-]+", line)
parents[parent].append((id_, name))
Traceback (most recent call last):
File "<ipython-input-29-2b2fd98946b3>", line 1, in <module>
runfile('/home/bob/Documents/mega/tree/python/structure.py', wdir='/home/bob/Documents/mega/tree/python')
File "/home/bob/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/home/bob/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
builtins.execfile(filename, *where)
File "/home/bob/Documents/mega/tree/python/structure.py", line 15, in <module>
for i, line in enumerate(istream.split(',')):
AttributeError: 'file' object has no attribute 'split'
【问题讨论】:
-
您能准确地向我们展示您正在运行的代码,以及错误的完整堆栈跟踪吗?
-
一方面,您在
,上进行拆分,但 CSV 文件中没有。 -
@Kenney,感谢您的回复。是逗号分隔的,只是我从liboffice复制粘贴过来的
-
@TomDalton 感谢您的回复。我刚刚发布了链接中的第二个,我尝试了多种获取文件的组合,这只是最新的。所有错误都出现在同一行。
-
另外,在上面的代码中,` ','` 已经绝望地尝试过了。我也用过
'\n'。