2016-11-21 57 views
0

我正在從文件p2.txt中讀取一個數字。此文件contrains只有1號是一個整數可以說10使用python從另一個文件中讀取單個數字

test_file = open('p2.txt', 'r') 
test_lines = test_file.readlines() 
test_file.close() 
ferNum= test_lines[0] 
print int(ferNum) 

不過時,我得到一個錯誤

print int(ferNum) 
ValueError: invalid literal for int() with base 10: '1.100000000000000000e+01\n' 

我可以看到,它正在考慮它就像一條線。我怎樣才能把這個數字解析成一個變量?有什麼建議麼?至於

+3

你應該包括輸入,否則你會收到狂野的猜測 – JuniorCompressor

回答

3

的問題是,即使數的是一個整數(11),它在科學記數法表示,所以你不得不讀它作爲float第一。

>>> float('1.100000000000000000e+01\n') 
11.0 

>>> int('1.100000000000000000e+01\n') 
Traceback (most recent call last): 
    File "<pyshell#4>", line 1, in <module> 
    int('1.100000000000000000e+01\n') 
ValueError: invalid literal for int() with base 10: '1.100000000000000000e+01\n' 

當然,你可以先來個float然後將轉換爲之後的int

>>> int(float('1.100000000000000000e+01\n')) 
11 
相關問題