2016-09-13 149 views
1

我读的列可变数量的文件列的数目可变的文件,说3个固定柱+未知/变量数列:阅读与蟒蛇

21 48 77 
15 33 15 K12 
78 91 17 
64 58 24 R4 C16 R8 
12 45 78 Y66 
87 24 25 
10 33 75 
18 19 64 CF D93 

我想存储第一在特定的列表/数组中有三个列条目,因为我需要使用它们,同时将所有剩余部分(从列[2]到行尾)放在另一个单独的字符串中,因为我不需要采取行动,但只是为了复制它。

我写道:

import os, sys 
import numpy as np 

fi = open("input.dat", "r") 
fo = open("output.dat", "w") 

for line in fi: 
    line = line.strip() 
    columns = line.split() 
    A00 = str(columns[0]) 
    A01 = str(columns[1]) 
    A02 = str(columns[2]) 
    A03 = EVERTHING ELSE UNTIL END OF LINE 

是否有一个简单的方法来做到这一点?提前致谢。

回答

1

您可以使用此代码:

import os, sys 
import numpy as np 
fi = open("input.dat", "r") 
fo = open("output.dat", "w") 
column_3 = [] 

for line in fi: 
    line = line.strip() 
    columns = line.split() 
    A00 = str(columns[0]) 
    A01 = str(columns[1]) 
    A02 = str(columns[2]) 
    column_3.append(str(columns[3])) 
print(column_3) 
0

我觉得下面的代码片段可以帮助你。另外,您可以为您的项目编辑此代码。

f = open("input.dat") 

line = f.readline().strip() # get the first line in line 

while line: # while a line exists in the file f 
    columns = line.split('separator') # get all the columns 
    while columns: # while a column exists in the line 
     print columns # print the column 
    line = f.readline().strip() # get the next line if it exists 

我希望它可以帮助你。

1

字符串分割允许限制提取部件的数目,这样就可以做以下:

A00, A01, A02, rest = line.split(" ", 3) 

实施例:

print "1 2 3 4 5 6".split(" ", 3) 
['1', '2', '3', '4 5 6'] 
+0

替代地,也可以这样做:'A00,A01,A02,* rest = line.split()'这会将'rest'变成一个像这样的列表:'rest = ['4','5','6']'。请注意,即使剩余的元素是单个元素(例如'rest = ['4']'),“rest”仍然是一个列表。 –