[英]Read columns from file where first row is string
What I would like to do is to read in columns from a .dat
file. 我想做的是从
.dat
文件中读取列。 I have been able to do this using scitools.filetable.read_columns()
. 我已经能够使用
scitools.filetable.read_columns()
做到这一点。 The problem that I am having is that the first row of my .dat
file contains strings
. 我遇到的问题是
.dat
文件的第一行包含strings
。 How can I skip the first row? 如何跳过第一行?
So for a short example I have the following .dat
file: 因此,作为一个简短示例,我具有以下
.dat
文件:
a b c d e
1 3 5 7 9
2 4 6 8 10
From this type of .dat
file I want to create arrays for each column without the string
. 从这种类型的
.dat
文件中,我想为每个没有string
列创建数组。 When the .dat file would not contain a,b,c,d,e
it would be very easy as it would just be: 当.dat文件不包含
a,b,c,d,e
,它将非常简单,因为它只是:
import scitools.filetable
fp = open("blabla.dat", "r")
a, b, c, d, e = scitools.filetable.read_columns(fp)
Now a
would read: [1 2]
. 现在
a
将显示为: [1 2]
。
However, when I try to do the same thing when a
, b
, c
, d
, and e
are part of the .dat
file, as indicated in my example, scitools
does not work since it cannot convert a string
to a float
. 但是,如我的示例所示,当
a
, b
, c
, d
和e
是.dat
文件的一部分时,当我尝试做同样的事情时, scitools
不起作用,因为它无法将string
转换为float
。 How can I open the file without the first row or create the desired columns? 如何在没有第一行的情况下打开文件或创建所需的列?
fp.next
to advance one line further fp.next
进一步前进一行 As fp
is file descriptor for file open in text mode, iterating over it reads it line by line. 由于
fp
是在文本模式下打开文件的文件描述符,因此对其进行迭代读取会逐行读取它。
You can ask fp
to read one line further by fp.next()
and then pass it to your `scitools.filetable.read_colums(fp) 您可以要求
fp
通过fp.next()
进一步读一行,然后将其传递给您的`scitools.filetable.read_colums(fp)
Your code would look like this after modification: 修改后的代码如下所示:
import scitools.filetable
fp = open("blabla.dat", "r")
fp.next()
a, b, c, d, e = scitools.filetable.read_columns(fp)
Or using context manager for closing the file: 或使用上下文管理器关闭文件:
import scitools.filetable
with open("blabla.dat", "r") as fp:
fp.next()
a, b, c, d, e = scitools.filetable.read_columns(fp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.