如何使用python和文件解析从每行中获得第二件事

2024-10-03 09:14:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解析一个具有以下结构的文件:

0   rs41362547  MT  10044
1   rs28358280  MT  10550
...

以此类推,我想把每行的第二个东西放到一个数组中。我知道这应该很容易,但经过一番寻找,我还是迷路了。我对python真的很陌生,那么脚本是什么呢?你知道吗

谢谢!你知道吗


Tags: 文件脚本数组结构mt陌生迷路rs41362547
2条回答

这将起作用:

with open('/path/to/file') as myfile:       # Open the file
    data = []                               # Make a list to hold the data
    for line in myfile:                     # Loop through the lines in the file
        data.append(line.split(None, 2)[1]) # Get the data and add it to the list
print (data)                                # Print the finished list

这里的重要部分是:

  1. ^{},它根据空格分隔行。

  2. with-statement,完成后自动关闭文件。


请注意,您还可以使用list comprehension

with open('/path/to/file') as myfile:
    data = [line.split(None, 2)[1] for line in myfile]
print (data)

可以使用^{}拆分行:

with open('file.txt') as infile:
    result = []
    for line in infile: #loop through the lines
        data = line.split(None, 2)[1] #split, get the second column
        result.append(data) #append it to our results
        print data #Just confirming

相关问题 更多 >