我正在运行Python 2.7。我对Python很陌生。我正在尝试读取CSV文件(值由空格分隔),并根据坐标上方的标题分隔内部值。该文件的格式不是我习惯的,我无法正确读取值。即使我能让他们正确阅读,我也不知道如何将它们放入列表中。使用Python读取CSV文件2
下面是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
所以我m试图让程序根据标题分开坐标,然后将它们放入单独的列表中。感谢您的帮助!
那不是真的* * CSV文件,所以它可能不适合使用'CSV .reader'。示例输入文件需要的输出是什么? – Aya
我不明白行'if row!= int:'??? –
我最终希望使用reader/parser的输出作为我正在绘制的图形的坐标。所以我想,列表中的x和y坐标与它们在输出中的方式一起。我应该用什么来代替csv.reader? – user2479054