python 读入文件指定列_将文本文件的特定列读入列表(Python3.6.3)

本文介绍了一个Python函数,用于读取文本文件的指定列,并可选择转换数据类型和列分隔符。函数`read_col`接受文件名、列索引、转换函数和分隔符作为参数,允许灵活地处理数据。示例展示了如何读取不同格式的文件,如读取第一列、转换为浮点数或跳过首行。
摘要由CSDN通过智能技术生成

解决方案

听起来像是一个小助手函数: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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值