我有一个文本文件,它包含了前20行左右的文本,后面是CSV数据。文本部分的某些文本包含逗号等csv.reader文件或者csv.dictreader文件效果不好。你知道吗
我想跳过文本部分,然后才开始解析CSV数据。你知道吗
搜索不会产生太多其他的指令来使用csv.reader/csv文件.dictreader并遍历返回的行(由于文本中有逗号,因此无法工作),或者逐行读取文件并使用''作为分隔符拆分行。你知道吗
后者在一定程度上起作用,但它产生的是字符串,而不是数字。我可以将字符串转换成数字,但我希望有一种简单的方法可以通过csv或numpy库来实现。你知道吗
根据要求-样本数据:
This is the first line. This is all just text to be skipped. The first line doesn't always have a comma - maybe it's in the third line Still no commas, or was there? Yes, there was. And there it is again. and so on There are more lines but they finally stop when you get to EndOfHeader 1,2,3,4,5 8,9,10,11,12 3, 6, 9, 12, 15
谢谢你的帮助。你知道吗
编辑#2 建议的答案给出了以下链接,标题为Read file from line 2... 这正是我要找的,但我希望能够通读这些行,直到找到“EndOfHeader”,然后调用CSV库来处理文件的其余部分。 答复saimadhu.polamuri公司是我尝试的一部分,特别是
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
#test if line equals EndOfHeader. If true then parse as CSV
但这就是它的不同之处-我不知道如何让CSV从现在开始处理数据。你知道吗
感谢@Mike的建议,代码实际上相当简单。你知道吗
在我的实际代码中,它将搜索EndOfHeader行并使用它来决定从何处开始解析CSV
我把这个作为一个答案,因为这个问题,这个假设重复没有明确考虑这个问题的文件句柄,以及它如何可以传递到一个CSV阅读器,所以它可能会帮助其他人。你知道吗
感谢所有花时间帮忙的人。你知道吗
相关问题 更多 >
编程相关推荐