计算两个文件之间的商数并写入到另一个文件

计算两个文件之间的商数并写入到另一个文件

问题描述:

使用Python,我有两个大的(同样长)文件中的数字之间用空格分开:计算两个文件之间的商数并写入到另一个文件

0.11158E-13 0.11195E-13 0.11233E -13#...文件1

0.11010E-13 0.11070E-13 0.11117E-13 ...#文件2

有在价值观念的差异,我想获得的相对差异,写他们以相同的格式转换成第三个文件。 我可以为第一个值做到这一点,但在ITERATING过程中有问题(以便计算所有值)。

这是代码(我是新来的Python代码):

with open('ex1.idl', 'r') as f1:  #this opens the first file 
    with open('ex2.idl', 'r') as f2:  #this opens the second file 

     f1 = f1.read(13)   # reading the length of the value (ex1.idl) 
     f2 = f2.read(13)   # reading the length of the value (ex2.idl) 
     f1 = float(f1)   #assigning the numerical value for the string 
     f2 = float(f2)   #assigning the numerical value for the string 
     c = f1/f2    #calculating relative values  

with open('ex3.txt', 'w') as f3:   #opening the new file and 
    f3.write(str(c))      #writing into the new file as a string 

这是去还是我应该去用不同的方式的方式吗?非常感谢答复。

它看起来像你的文件有一行。因此,在每个文件中获取数字的最简单方法是只读取文件的全部内容,去除不需要的字符,然后拆分分隔浮点值的空白。分割空间会给你一个strings的列表,然后你可以强制到floats。此时,您应该有两个浮点值列表,那就是当您使用zipmap函数的组合执行除法操作时。下面是一个例证:

with open('ex1.idl') as f1, open('ex2.idl') as f2: 
    with open('ex3.txt', 'w') as f3: 
     f1 = map(float, f1.read().strip().split()) 
     f2 = map(float, f2.read().strip().split()) 
     for result in map(lambda v: v[0]/v[1], zip(f1, f2)): 
      # This writes the results all in one line 
      # If you wanted to write them in multiple lines, 
      # then you would need replace the space character 
      # with a newline character. 
      f3.write(str(result)+" ") 

我希望这个证明是有用的。

+0

谢谢,它帮助。我还有一个问题: 碰巧所需的数据位于文件的某一行深处。我希望这将达到目的: \t \t F1 = f1.readlines()[905]/n的 \t \t F2 = f2.readlines()[905]/n的 \t \t 我后最后插入该打开命令(f3 :)。这两行应该可以工作,但似乎它们与其余的不兼容。 – Robert

+0

嗨@罗伯特我不知道我关注。你可以编辑你的问题,并添加这些编辑?否则,您可以在考虑这些说明的同时提出一个新问题。 – Abdou

+0

会做:)认为它不会那么清楚。 – Robert