2017-08-17 72 views
1

使用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 

這是去還是我應該去用不同的方式的方式嗎?非常感謝答覆。

回答

0

它看起來像你的文件有一行。因此,在每個文件中獲取數字的最簡單方法是隻讀取文件的全部內容,去除不需要的字符,然後拆分分隔浮點值的空白。分割空間會給你一個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

相關問題