我运行的是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所以我试着让程序根据头部来分离坐标,然后把它们放到不同的列表中。谢谢你的帮助!
发布于 2013-06-13 00:11:46
看看pandas吧。它有一个DataFrame对象,可以保存你的数据并允许你以一种直观的方式进行操作。它还有一个read_csv函数,在处理csv文件时省去了很多麻烦。
例如:
import pandas as pd
#reads your csv file in and returns a DataFrame object as metioned above.
df = pd.read_csv("your_csv.csv", sep=' ', names=['co_a','co_b'], header=None, skiprows=2)
#extracts your discordant to separate lists
list1 = df.co_a.to_list()
list2 = df.co_b.to_list()您可以使用df或df.head()查看数据框架以及数据是如何管理的。值得一提的是,df.co_a是一个Series对象,想象一下超级列表/字典,您可能可以从那里进行分析或操作。
另外,如果您向我展示csv文件中的注释是如何存在的,那么我可以向您展示如何使用read_csv忽略它们。
我知道您正在寻找csv module的答案,但这是一个更高级的工具,从长远来看可能会对您有所帮助。
希望它能帮上忙!
发布于 2013-06-13 00:14:21
实际上,你的代码对我来说运行得很好。我不知道你为什么要追查。
tmp.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
# endtmp.py
import csv
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("tmp.csv", "rb")),
delimiter=' ')
for row in tsv_file:
if row != int:
next(tsv_file)
if row:
print rowShell输出
tmp$python tmp.py
['1.png']
['200', '100']
['300', '300']
['2.png']
['200', '100']
['135', '322']
tmp$uname -mprsv
Darwin 12.4.0 Darwin Kernel Version 12.4.0: Wed May 1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 i386
tmp$python --version
Python 2.7.2https://stackoverflow.com/questions/17070071
复制相似问题