从python中读取文件,拆分

时间:2014-11-10 21:54:44

标签: python input

使用文件输入和输出的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

3 个答案:

答案 0 :(得分:1)

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

1.更改

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

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

2.Change:

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

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

这将使您的代码正常工作。它的作用是将所有输入转换为浮点数,然后将balance和term转换为整数,以便它们可以在for循环中使用。我在我的电脑上试过代码,应该可以正常工作。

答案 1 :(得分:0)

查看异常回溯。错误发生在第11行,它基本上表示“&#39; 5.5&#39;不是一个int。这是正确的 - 它是一个浮点数(小数)。 第11行目前是:

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

尝试:

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

答案 2 :(得分:0)

您尝试在小数值上调用int(),或在python中调用float。这就是为什么它无法正常工作的原因。 在交互式shell(IDLE)中尝试int('5.5'),你会得到同样的错误。

试试这个:

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

如果您不介意失去价值的精确度,这将完成工作,因为int会将它们四舍五入到整数,如果您不介意它们都是浮点数然后只使用float代替int