从python中的文本文件读取特定列 [英] Reading specific columns from a text file in python

查看:2459
本文介绍了从python中的文本文件读取特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含一个由数字组成的表格,例如:

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

5 10 6

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()]

split()

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

返回字符串s的单词列表.如果不存在可选的第二个参数sep或无",则单词将由任意的空白字符字符串(空格,制表符,换行符,返回值,换页符)分隔.如果存在第二个参数sep而不是None,则它指定一个字符串用作单词分隔符.这样,返回的列表将比字符串中不重复出现的分隔符的数量多一个项目.

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 argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.

因此,您可以省略我所使用的空间,而仅执行x.split(),但这也将删除制表符和换行符,请注意.

So, you can omit the space I used and do just x.split() but this will also remove tabs and newlines, be aware of that.

这篇关于从python中的文本文件读取特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆