【发布时间】:2018-06-01 00:26:57
【问题描述】:
我需要读取一个包含一行整数 (13 34 14 53 56 76) 的输入文件 (input.txt),然后计算每个数字的平方和。
这是我的代码:
# define main program function
def main():
print("\nThis is the last function: sum_of_squares")
print("Please include the path if the input file is not in the root directory")
fname = input("Please enter a filename : ")
sum_of_squares(fname)
def sum_of_squares(fname):
infile = open(fname, 'r')
sum2 = 0
for items in infile.readlines():
items = int(items)
sum2 += items**2
print("The sum of the squares is:", sum2)
infile.close()
# execute main program function
main()
如果每个数字都在自己的行上,则可以正常工作。
但是,当所有数字都在一行上,由空格分隔时,我不知道该怎么做。在这种情况下,我收到错误:ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'
【问题讨论】:
-
文件的具体内容是什么?
-
如果只是一行,请致电
data = infile.read(); for number in map(int, data.split()): sum2 += number ** 2 -
您的文件是包含空格分隔数字的单行吗?
-
是的,没错。这是文件的全部内容:13 34 14 53 56 76
-
@JonClements 是的,尽管对于家庭作业来说这可能有点太高级了。另外,不要忘记
int(num):-)
标签: python python-3.x integer readlines