2014-01-26 32 views
0

此代碼不會將輸出寫入文件。它只轉儲中的數據。數據文件不應該是一個範圍從0到1不將輸出寫入文件的代碼

import math 

f = open('numeric.sm.data', 'r') 
print f 


maximum = 0 

# get the maximum value 
for input in f: 
    maximum = max(int(input), maximum) 
f.close() 

print('maximum ' + str(maximum)) 


# re-open the file to read in the values 
f = open('numeric.sm.data', 'r') 
print f 

o = open('numeric_sm_results.txt', 'w') 
print o 

for input in f: 
    # method 1: Divide each value by max value 
    m1 = float(input)/(maximum) 
    o.write(input) 
    print repr(input.strip('\n')).rjust(5), repr(m1).rjust(5) 

o.close() 
f.close() 

回答

1
o.write(input) 

輸出應該是

o.write(str(m1)) 

,可能要添加一個換行符什麼:

o.write('{0}\n'.format(m1)) 
+0

我認爲這會增加你在談論 換行符printr repr(input.strip('\ n')).rjust(5),repr(m1).rjust(5) – user2428261

+0

@ user2428261不是,這會將某些內容打印到控制檯,但不打印到文件。 – Nabla

+0

好吧,它顯示了一個TypeError:期望在這條寫入命令 – user2428261

0

這是因爲你有文件處理程序調用f

,但它只是指向一個對象,而不是你的文件的內容

所以,

f = open('numeric.sm.data', 'r') 
f = f.readlines() 
f.close()and then, 

然後,

o = open('numeric_sm_results.txt', 'w') 

for input in f: 
    # method 1: Divide each value by max value 
    m1 = float(input)/(maximum) 
    o.write(input) # Use casting if needed, This is File write 
    print repr(input.strip('\n')).rjust(5), repr(m1).rjust(5) # This is console write 

o.close()