gpt4 book ai didi

python - 从Python中的文件读取,并进行分割

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:11 25 4
gpt4 key购买 nike

Python 3x 在文件输入和输出方面出现问题

所以,我正在为计算机科学课做作业,但遇到了一个小问题。我的教授希望我们添加一些代码行,要求程序打开一个 .txt 文件,并通过程序从 .txt 文件中读取数据。在本例中,我的程序是按月付款程序。通常,您会要求用户输入他/她的借款金额、利率和期限(以年为单位)。但是,所有这三个数据都已预先写入 .txt 文件中,他希望我们从中读取数据。现在,我的代码遇到了问题。

这是我的代码:

import decimal

print("\t".join(s.rjust(15) for s in ("Payment", "Amount Paid", "Balance")))
print("-"*54)

filename = "LoanData.txt"
values = []

with open(filename) as f:
for line in f:
values.append([int(n) for n in line.strip().split(' ')])
for arr in values:
try:
balance,rate,term = arr[0],arr[1],arr[2]
except IndexError:
print ("Index error occured, a line doesn't have the crucial amount of entries.")

balance *= (1 + rate * term)
payment = balance / (12 * term)
total = 0
for month in range(12 * term):
if balance < payment:
payment = balance
print(("{: >15.2f}\t"*3)[:-1].format(payment, total, balance))
total += payment
balance -= payment

这是我收到的错误:

Traceback (most recent call last):
File "C:/Users/Python/Desktop/loan.py", line 11, in <module>
values.append([int(n) for n in line.strip().split(' ')])
File "C:/Users/Python/Desktop/loan.py", line 11, in <listcomp>
values.append([int(n) for n in line.strip().split(' ')])
ValueError: invalid literal for int() with base 10: '5.5'

文件如下所示:

5000 5.5 10
25000 10.0 10
100000 8.5 20

最佳答案

这不起作用的原因是您正在尝试将十进制值(例如 5.5)转换为 int。现在,即使您将其更改为转换为 float ,仍然需要进行额外的修复,因为您不能使用 float 作为 for 循环的迭代器:

1.改变

balance,rate,term = arr[0],arr[1],arr[2]

balance,rate,term = int(arr[0]),arr[1],int(arr[2])

2.更改:

values.append([int(n) for n in line.strip().split(' ')])

values.append([float(n) for n in line.strip().split(' ')])

这将使您的代码正常工作。它的作用是将所有输入转换为 float ,然后将余额和术语转换为整数,以便它们可以在 for 循环中使用。我在我的电脑上尝试了该代码,它应该可以工作。

关于python - 从Python中的文件读取,并进行分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26853707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com