解决方案
听起来像是一个小助手函数:def read_col(fname, col=1, convert=int, sep=None):
"""Read text files with columns separated by `sep`.
fname - file name
col - index of column to read
convert - function to convert column entry with
sep - column separator
If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
"""
with open(fname) as fobj:
return [convert(line.split(sep=sep)[col]) for line in fobj]
res = read_col('mydata.txt')
print(res)
输出:
^{pr2}$
{cde>如果你想在第一列read_col('mydata.txt', col=0)
如果您希望它们是浮动的:read_col('mydata.txt', col=0, convert=float)
如果列之间用逗号隔开:read_col('mydata.txt', sep=',')
您可以使用这些可选参数的任意组合。在
解释
我们用默认参数定义了一个新函数:def read_col(fname, col=1, convert=int, sep=None):
这意味着您必须提供文件fname。所有其他参数都是可选的,如果在调用函数时没有提供默认值,则将使用默认值。在
在函数中,我们使用以下命令打开文件:with open(fname) as fobj:
现在,fobj是一个打开的文件对象。文件将在我们删除时关闭,也就是说,在这里,当我们结束函数。在
这个:[convert(line.split(sep=sep)[col]) for line in fobj]
通过遍历文件的所有行来创建列表。每条线在分隔符sep处拆分。我们只获取索引为col的列的值。{We}也转换成默认值cde}。在
编辑
也可以跳过文件中的第一行:with open(fname) as fobj:
next(fobj)
return [convert(line.split(sep=sep)[col]) for line in fobj]
或者更复杂的可选论点:def read_col(fname, col=1, convert=int, sep=None, skip_lines=0):
# skip first `skip_lines` lines
for _ in range(skip_lines):
next(fobj)
with open(fname) as fobj:
return [convert(line.split(sep=sep)[col]) for line in fobj]