Skip to main content
 首页 » 编程设计

python之使用python从数据文件中提取选定的列

2024年10月24日7qlqwjy

我有这样一个数据文件

0.000       1.185e-01  1.185e-01  3.660e-02  2.962e-02  0.000e+00  0.000e+00  0.000e+00  0.000e+00  0.000e+00 
0.001       1.185e-01  1.185e-01  3.660e-02  2.962e-02  -1.534e-02  -1.534e-02  8.000e-31  8.000e-31  0.000e+00 
0.002       1.185e-01  1.185e-01  3.659e-02  2.961e-02  -1.541e-02  -1.541e-02  -6.163e-01  -6.163e-01  -4.284e-05 
0.003       1.186e-01  1.186e-01  3.657e-02  2.959e-02  -1.547e-02  -1.547e-02  -8.000e-31  -8.000e-31  0.000e+00 
0.004       1.186e-01  1.186e-01  3.657e-02  2.959e-02  -2.005e-32  -2.005e-32  -8.000e-31  -8.000e-31  0.000e+00 
0.005       1.186e-01  1.186e-01  3.657e-02  2.959e-02  -2.005e-32  -2.005e-32  -8.000e-31  -8.000e-31  0.000e+00 
0.006       1.187e-01  1.186e-01  3.657e-02  2.959e-02  -2.005e-32  -2.005e-32  -8.000e-31  -8.000e-31  0.000e+00 
0.007       1.187e-01  1.187e-01  3.657e-02  2.959e-02  -2.005e-32  -2.005e-32  -8.000e-31  -8.000e-31  0.000e+00 
0.008       1.188e-01  1.187e-01  3.657e-02  2.959e-02  -2.005e-32  -2.005e-32  -8.000e-31  -8.000e-31  0.000e+00 
0.009       1.188e-01  1.187e-01  3.657e-02  2.959e-02  -2.005e-32  -2.005e-32  -8.000e-31  -8.000e-31  0.000e+00 

我只想将选定的列从该文件复制到另一个文件。假设我将第 1、2 和 6 列复制到一个文件中,那么该文件应该看起来像

0.000       1.185e-01  0.000e+00 
0.001       1.185e-01  -1.534e-02 
0.002       1.185e-01  -1.541e-02 
0.003       1.186e-01  -1.547e-02 
0.004       1.186e-01  -2.005e-32 
0.005       1.186e-01  -2.005e-32 
0.006       1.187e-01  -2.005e-32 
0.007       1.187e-01  -2.005e-32 
0.008       1.188e-01  -2.005e-32 
0.009       1.188e-01  -2.005e-32 

这是一个非常大的格式化文本文件,最初是这样写的

f=open('myMD.dat','w') 
s='%8.3e  %8.3e  %8.3e  %8.3e  %8.3e  %8.3e  %8.3e  %8.3e  %8.3e\t\t'%(xpos1[i],ypos1[i],xvel1[i],yvel1[i],xacc1[i],yacc1[i],xforc[i],yforc[i],potn[i]) 
f.write(s) 
f.close() 

我正在用 python 编程。我该怎么做?

请您参考如下方法:

简单得多,但用途广泛。假设所有字段都不包含任何空格,您可以简单地在每一行上使用 split 方法来获取字段列表,然后打印您想要的字段。这是一个脚本,可让您指定输出的列和分隔符字符串。

注意:我们决不会在字符串和 float 之间进行转换。这保留了以前的数字格式,对于一个巨大的文件,节省了大量的 CPU!

COLS=0,1,5  # the columns you want. The first is numbered zero. 
            # NB its a tuple: COLS=0, for one column, mandatory trailing comma 
 
SEP = ', '  # the string you want to separate the columns in the output 
 
INFILE='t.txt'      # file to read from 
OUTFILE='out.txt'   # file to write to 
 
f = open( INFILE, 'r') 
g = open( OUTFILE, 'w') 
 
for line in f.readlines(): 
   x = line.split() 
   if x != []:  # ignore blank lines 
 
       y = [ x[i] for i in COLS ] 
       outline = SEP.join( '{}'.format(q) for q in y ) 
       g.write( outline+'\n') 

刚刚意识到,'{}'.format(q) for q in y 在这里有点矫枉过正。 y 是要输出不变的字符串数组,因此 SEP.join(y) 就是您在这里所需要的。但是显示将格式应用于相似元素列表的模式可能很有用。