2012-06-15 20 views
4

如何在Python中打開文件並從文件中讀取文件中的字符串格式的文件?我還想更改每個浮點數的值,並用新值重寫文件。如何讀取文件中的浮點數?

+1

只要您有什麼部分有問題嗎? –

回答

3

「float()」函數接受字符串作爲輸入並將它們轉換爲浮點數。

>>> float("123.456") 
123.456 
1
def get_numbers(): 
    with open("yourfile.txt") as input_file: 
     for line in input_file: 
      line = line.strip() 
      for number in line.split(): 
       yield float(number) 

然後把它們寫回當你做

,並作爲一個較短的版本(沒有測試過,從磁頭寫入)

with open("yourfile.txt") as input_file: 
    numbers = (float(number) for number in (line for line in (line.split() for line in input_file))) 
12

假設有每行一個浮動:

with open("myfile") as f: 
    floats = map(float, f) 

# change floats 

with open("myfile", "w") as f: 
    f.write("\n".join(map(str, floats))) 

如果您想要格式化更多控制,請使用字符串format method。舉例來說,這樣只會每個週期後打印3個數字:

f.write("\n".join(map("{0:.3f}".format, floats))) 
0
如果你想讀input_num花車

import numpy as np 
import struct 
float_size=4 
np.array(struct.unpack('<'+str(input_num)+'f', 
        fin.read(float_size*input_num))) 
相關問題