我正在尝试解析具有结构的文件:
0 rs41362547 MT 10044
1 rs28358280 MT 10550
...
依此类推,我希望每一行中的第二件事都放入一个数组中。我知道这应该很容易,但经过大量的搜索,我仍然迷失了。我是python的新手,这样做的脚本是什么?
谢谢!
答案 0 :(得分:4)
您可以使用str.split
分割线条:
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
答案 1 :(得分:3)
这将有效:
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
这里的重要部分是:
str.split
,根据空格分隔行。
with-statement,完成后自动为您关闭文件。
请注意,您还可以使用list comprehension:
with open('/path/to/file') as myfile:
data = [line.split(None, 2)[1] for line in myfile]
print (data)