python怎么读取txt文件的某一列-从python中的文本文件读取特定列

本文介绍如何从包含数字的txt文件中提取第二列内容到列表。通过使用`split()`函数,可以按空格切分行并获取指定列。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

I have a text file which contains a table comprised of numbers e.g:

5 10 6

6 20 1

7 30 4

8 40 3

9 23 1

4 13 6

if for example I want the numbers contained only in the second column, how do i extract that column into a list?

解决方案f=open(file,"r")

lines=f.readlines()

result=[]

for x in lines:

result.append(x.split(' ')[1])

f.close()

You can do the same using a list comprehension

print [x.split(' ')[1] for x in open(file).readlines()]

Docs on split()

string.split(s[, sep[, maxsplit]])

Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argume

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值