如何在python中读写特定的数字到文本?

时间:2015-01-16 21:18:54

标签: python

我是python的新手我有两个大文本文件(输入和输出)。 我想从输出(x3,x5,x6)读取一些浮点值,并将这些值写入特定部分而不是旧值(y1,y3,y5)到输入中。 我有一个项目,我必须为这项工作编写一个脚本。我需要你的帮助。我尝试像下面这样做python,但它不起作用。

  a='Flux'

with open('data.txt',"r+") as f:

with open('output.txt',"r+") as f:    
for line in f:
   if a in line:
       for line in f:
           print line
           break       

     f.close()

  output

  ....

  ....

  [flux][1]

        x1            x2          x3        x4           x5          x6
  1  1.3669E+01  4.9079E-01  7.4414E-03  4.2656E-01  9.4185E-02  1.2263E-01  
  2  1.3828E+01  4.9120E-01  7.4390E-03  4.2583E-01  9.4543E-02  1.2313E-01  
  3  1.4079E+01  2.6339E-01 -4.0824E-09  4.2471E-01  3.9748E-03  0.0000E+00  
  4  1.4302E+01  1.7203E+00  4.9458E-01  4.2361E-01  1.2888E-02  0.0000E+00  

input

 ....
 ....
     y1            y2          y3          y4            y5          y6

0.734200E+00 0.734200E+00 0.265800E+00 0.449764E+02 0.575000E+03 0.107900E+04
0.000000E+00 0.216415E+00 0.225200E-02 0.000000E+00 0.000000E+00 0.000000E+00
0.109465E+01 0.667600E-01 0.000000E+00 0.000000E+00 0.000000E+00 0.343321E+00
0.694839E-03 0.000000E+00 0.000000E+00 0.000000E+00 0.155423E+01 0.947885E-01
0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 0.237800E-04 0.000000E+00 
0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 0.000000E+00 
0.000000E+00 0.000000E+00 0.333841E+02 0.000000E+00 0.000000E+00 0.000000E+00 
0.000000E+00 0.154468E+04 0.000000E+00 0.000000E+00 0.000000E+00

1 个答案:

答案 0 :(得分:2)

电离层的电子密度是多少? 所以我认为最好的方法是分割每行输出和输入文件并构造新的输出。像这样的人:

#!/usr/bin/python

with open('1.txt',"r+") as in1:
    with open('2.txt',"r+") as in2:  
        with open ('newout.txt','w') as newout:
            inlines1 = in1.readlines()
            inlines2 = in2.readlines()

            for i,j in inlines1,inlines2:
                buff = []
                i = i.split()
                j = j.split()
                buff.append(i[1]) #or any elems you want
                buff.append(j[2]) #or any elems you want
                buff = ' '.join(buff)
                newout.write('%s\n'%buff)

这是输入和输出的示例:

$ cat 1.txt 
1 3 5 7 
2 4 6 8


$ cat 2.txt 
2 4 6 8  
1 3 4 6


$ cat newout.txt 
3 6
4 4