我正在运行 Python 2.7。我对 Python 很陌生。我正在尝试读取一个 CSV 文件(值由空格分隔)并根据坐标上方的标题分隔内部的值。文件的格式不是我习惯的格式,我无法正确读取这些值。即使我能让它们正确阅读,我也不明白如何将它们放入列表中。
CSV 文件如下所示:
# image name
1.png
# probe locations
100 100
200 100
100 200
300 300
# another image name
2.png
100 200
200 100
300 300
135 322
# end
这是我正在玩的代码:
class CommentedFile:
def __init__(self, f, commentstring="#"):
self.f = f
self.commentstring = commentstring
def next(self):
line = self.f.next()
while line.startswith(self.commentstring):
line = self.f.next()
return line
def __iter__(self):
return self
#I did this in order to ignore the comments in the CSV file
tsv_file = csv.reader(CommentedFile(open("test.exp", "rb")),
delimiter=' ')
for row in tsv_file:
if row != int:
next(tsv_file)
if row:
print row
代码打印出来:
['100', '100']
['100', '200']
['100', '200']
['300', '300']
Traceback (most recent call last):
File "the path", line 57, in <module>
next(tsv_file)
StopIteration
所以我试图让程序根据标题分离坐标,然后将它们放入单独的列表中。谢谢您的帮助!