![](/img/trans.png)
[英]Python3.7.1: `10**3.5`: could not convert string to float: 3.5
[英]Python 3.7.1 “ValueError: could not convert string to float:”
我嘗試讀取文件的內容並將其保存為變量,並嘗試將其轉換為float並-
Traceback (most recent call last):
File "/Users/username/wageCalculator.py", line 26, in <module>
writeTotal.write(str(float(total)+float(getBal)))
TypeError: float() argument must be a string or a number, not '_io.TextIOWrapper
這是編輯后的代碼:(更改的目錄名稱)年齡
import time
while True:
wage = 5
moneyPerSecond=(int(wage)/3600)
moneyPerMinute=(int(wage)/60)
print('Your wage per second is: $'+str(moneyPerSecond))
print('Please input the amount of minutes you worked. It must be a whole number.')
minutesWorked = input()
minuteWage = int(minutesWorked)*float(moneyPerMinute)
print('Please input the amount of seconds you worked. It can be a decimal.')
secondsWorked = input()
secondWage = float(secondsWorked)*float(moneyPerSecond)
print('Your total is: $' + str(float(minuteWage)+float(secondWage)))
total = float(minuteWage)+float(secondWage)
getBal = open('/Users/username/balance.txt','r+')
readBal = getBal.read()
getBal.close()
print('Current balance: $' + str(readBal))
print('Do you want to add this to your balance?')
print('Key in "y" for yes or "n" for no and press enter:')
yesOrNo = input()
if yesOrNo=='y':
open('/Users/username/balance.txt','w').close
writeTotal = open('/Users/username/balance.txt' ,'a')
writeToLog = open('/Users/username/balanceLog.txt','a')
writeToLog.write(str(total))
writeTotal.write(str(float(total)+float(readBal)))
writeTotal.close()
writeToLog.close()
elif yesOrNo=='n':
print('Reseting...')
time.sleep(1)
else:
print('Please try again.')
我曾嘗試將其轉換為字符串,但它給了我同樣的錯誤。
任何人都能找到答案,那就太好了。 :p
編輯:我已經嘗試過getBal和readBal,而readBal給了我這個錯誤:
Traceback (most recent call last):
File "/Users/Jonathan_Xu/wageCalculator.py", line 27, in <module>
writeTotal.write(str(float(total)+float(readBal)))
ValueError: could not convert string to float:
錯誤中的代碼行與發布的代碼不匹配:
writeTotal.write(str(float(total)+float(getBal)))
與
writeTotal.write(str(float(total)+float(readBal)))
大概您打算使用float(readBal)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.