【发布时间】:2013-06-12 15:57:10
【问题描述】:
我正在运行 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
所以我试图让程序根据标题分隔坐标,然后将它们放入单独的列表中。感谢您的帮助!
【问题讨论】:
-
那不是真的 CSV 文件,因此使用
csv.reader可能不合适。您希望示例输入文件的输出是什么? -
看不懂
if row != int:这行??? -
我最终想使用阅读器/解析器的输出作为我正在绘制的图形的坐标。因此,我认为,一个列表与 x 和 y 坐标在一起,就像它们现在在输出中的方式一样。我应该使用什么来代替 csv.reader?
-
Sylvain -- 我试图让它检查该行中是否有数字或字母,但我知道这不起作用......
-
您想接受任何答案吗?你能解决你的问题吗?