python - 尝试编写一个 python 程序,从文件中读取数字并计算平方和

标签 python

我正在尝试编写一个程序,从文件中读取数字,然后计算这些数字的平方和。该程序应该提示用户输入文件名并打印平方和。它提供了一个提示,说使用 readlines() 但这对我没有太大帮助。我已经尝试了好几个小时来想出一个有效的代码,但什么也做不了!!!我准备拔头发了!!!这是我的代码:

我的文件代码:

def main():
    filename = input("Enter the name for the file: ")
    infile = open(filename, 'w')
    numList = input('Enter any numbers(seperated by a space): ')
    print(numList, file=infile)

main()

我的程序代码:

# function to convert list of strings to real numbers
def toNumbers(nums):
    for i in range(len(nums)):
        nums[i] = int(nums[i])

# function to square the numbers in a list
def numsquare(nums):
    for i in range(len(nums)):
    nums[i] = nums[i]**2

# function to add the numbers in the list
def sumList(nums):
    total = 0
    for i in nums:
        total = total + i
    return total

# program that pulls numbers from file and computes sum of the square of the numbers
def main():
fname = input("Please enter the name of the file to be opened: ")
nums = open(fname, 'r')

print("The numbers in this list are:")
print(nums)

# Convert strings in list to actual numbers
toNumbers(nums)
# Square the numbers in the list
numsquare(nums)
# Get the sum of the numbers in the list
sumList(nums)

total = sumList(nums)

print()
print("The sum of the numbers from this list is:", total)


main()

如果有人能告诉我我做错了什么,将不胜感激。这是我第一次上计算机科学课,欢迎任何建议。

最佳答案

在不知道文件结构的情况下,我至少可以告诉你你的部分问题是你使用文件句柄作为你的“nums”变量,这不会给你你的内容。

为了从文件中提取数据,您需要在文件句柄上调用 .read() 或 .readline()。

fname = input("Please enter the name of the file to be opened: ")
file = open(fname, 'r')

lines = file.readlines()

lines 现在包含一个列表,其中每个条目都是文件一行的内容

如果您每行有一个数字,您应该能够将每个列表条目的内容转换为一个 int 以获得数字列表。

如果每行有多个数字,则需要在每个列表条目上使用 split() 来提取每个单独的数字。

关于python - 尝试编写一个 python 程序,从文件中读取数字并计算平方和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025358/

相关文章:

python - python wave模块可以接受StringIO对象吗

python - r'\' 不应该是 python 中的有效字符串值吗?

python - 将缩进代码向左移动,删除前导标签

python - 如何定义当用户在 TextInput 中输入文本并在 Kivy 中按 Enter 时会发生什么?

python - mod.predict 给出的列比预期多

python - 确保带有子进程的 Python 脚本在 SIGINT 上死掉

python - 如何设计一个扭曲的解决方案来通过读取特定部分来下载文件?

python - 如何验证 HttpResponseRedirect 是否指向外部站点?

python - 如何在 Django 或 Flask 中嵌入交互式 Bokeh 或 Dash 应用*带身份验证*?

python - 'RegisterForm' 对象没有属性 'is_valid'