嘿傢伙,所以我有一個文本文件,我試圖讀取並接收每個數字字符串 並將其轉換爲浮點數。但每次我嘗試它時,都會說「cannont convert string to float」。這是爲什麼發生?謝謝!如何將字符串轉換爲浮動當從文本文件中讀取
try:
input_file = open("Dic9812.TFITF.encoded.txt","r")
output_fileDec = open("Dic9812.TFITF.decoded.txt","w")
output_fileLog = open("Dic9812.TFITF.log.txt","w")
except IOError:
print("File not found!")
coefficientInt = input("Enter a coefficient: ")
coefficientFl = float(coefficientInt)
constInt = input("Enter a constant: ")
constFl = float(constInt)
try:
for line in input_file:
for numstr in line.split(","):
numFl = float(numstr)
print(numFl)
except Exception as e:
print(e)
文件看起來是這樣的:
135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0
它結束了印刷的數字,但在最後它說: 不能把字符串轉換爲float:
首先,您能不能告訴你試圖解析該文件的例子嗎? –
其次,告訴我們'cannont convert string to float'發生在哪一行。 – 2014-02-21 21:40:10
你確定*文件中有'etc'嗎?請發佈一些*真實*行。 – 2014-02-21 21:45:14