Python.txt文件&while循环
问题: 在main中,创建一个空列表。 打开名为scores.txt的文件,并使用一个while循环来检测文件的结尾以读取分数,并将其添加到列表中,然后关闭该文件。 使用分数列表作为唯一参数调用showscores函数。 在showscores函数中,处理分数列表。 打印平均分数,精确到小数点后两位。 这是scores.txt,其中包含5个数字的列表。文件中的数字是垂直排列的,如下所示: 我现在有以下代码,但不断出现这些错误: 第19行,在 主要 第17行,总机 showscorescores 第2行,在showscores中 总分=总分 TypeError:不支持+:“int”和“str”的操作数类型Python.txt文件&while循环,python,Python,问题: 在main中,创建一个空列表。 打开名为scores.txt的文件,并使用一个while循环来检测文件的结尾以读取分数,并将其添加到列表中,然后关闭该文件。 使用分数列表作为唯一参数调用showscores函数。 在showscores函数中,处理分数列表。 打印平均分数,精确到小数点后两位。 这是scores.txt,其中包含5个数字的列表。文件中的数字是垂直排列的,如下所示: 我现在有以下代码,但不断出现这些错误: 第19行,在 主要 第17行,总机 showscorescores
def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))
def main():
scores = []
scores_file = open("scores.txt", 'r')
line_list = list(scores_file.readlines())
i = 0
while i < len(line_list):
scores.append(line_list[i])
i += 1
scores_file.close()
showscores(scores)
main()
我已经尝试过这个方法,效果很好:
def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))
def main():
f = open("PATH TO YOUR FILE", 'r')
content = list(f.readlines())
scores = []
for x in content:
scores.append(int(x.replace(" ", "")))
showscores(scores)
main()
希望这对你有用这是一项相当简单的任务
def showscores(scores):
# calculate average with two decimal place
print '%.2f' % (float(sum(scores)) / len(scores))
if __name__ == '__main__':
scores = []
f_obj = open('scores.txt') # open scores.txt
for line in f_obj.readlines(): # read line by line
if line.strip() == '': # skip empty line
continue
else: # add score to scores list
scores.append(int(scores))
f_obj.close() # close file.
showscores(scores) # call showscores function
具有异常处理的解决方案
代码:
输出:
与语句和映射函数一起使用:
#- Read file content.
with open(file_name, "rb") as fp:
content = fp.read()
#- Get all numbers from the file content by RE and map.
scores = map(int, re.findall("\d+", content))
return scores
这里没有人真的在帮助他。很明显,OP刚刚开始学习编程,在解决这个问题上遇到了一些问题。对吧? 给他所有的解决方案只是为了得到一些代表是不行的 我认为OP面临着一个练习或家庭作业,并且已经确定了要遵循的步骤 哦,一开始很难,但会好起来的 描述似乎会给您带来更多麻烦的部件: 您需要打开该文件,为此,您可以读取sshashank124提供给您的链接。 while希望您逐行读取文本文件,这就是为什么需要while循环,以便对每行重复相同的操作。对于每一行,将其内容添加到先前创建的列表中。 将该列表提供给需要编码的函数showscores,如果我理解您收到的指示,您将在那里处理数据。因为你现在的名单上有什么?每行的字符串。对其进行处理,以便将其转化为更实际的数字。 从那里,你现在可以计算出你被要求的平均值,并显示出来。 有关代码示例,请检查其他答案。尽管他们可能会麻烦你,因为他们看起来不友好。如果您遇到任何问题,请不要忘记使用收藏夹搜索引擎,阅读文档等 编辑:您似乎特别难以处理while循环。下面是一个小代码来展示它 在此之前,请查看该小教程,了解其背后的基本原理: 因此,这里不是为您实现所有功能的神奇for循环,而是您如何使用while实现它:
这项工作已经完成。这就是最终起作用的原因:
def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))
def main():
scores = []
scores_file = open('scores.txt', 'r')
line_list = list(scores_file.readlines())
scores_file.close()
i = 0
while i < len(line_list):
scores.append(int(line_list[i].strip()))
i += 1
showscores(scores)
main()
阅读有关文件I/O的相关部分:您是否搜索了产生的异常?我相信还有很多人和你有同样的问题,包括在这个网站上,他们的问题得到了解决。不要成为一个帮助吸血鬼!!基本上,正如例外情况所说,您正在尝试将字符串添加到int中。您首先需要将该字符串转换为int,并可能对其进行格式化,然后才能执行此操作。在哪一行引发该异常?复制到这里的代码不应该出现这种情况。第7行在showscores sum_scores=sumscores第28行,主showscores第30行,在主showscores中,一直在谷歌搜索和研究错误,但是根据我所看到的,我所做的更改不起作用或不需要…是的,我不知道…在过去的两个小时里一直在搜索,但找不到它…在这个过程中使用的while循环在哪里?只是想了解一切。谢谢。@JohnFinger A for loop实际上只是一个奇特的while loop。在Python中,它们更受欢迎,但学习者通常会先学习while循环,以帮助他们提高逻辑技能。当使用while循环时,您必须自己处理索引,通常在每次迭代结束时递增索引,因为索引是为您完成的。通过一些知识/理解,您可以轻松地将for循环重写为while循环。特别是因为,如果你有家庭作业或类似的东西,你应该在一段时间内使用,而不是其他东西。祝你好运。这就是我现在一直在尝试做的事情,而且似乎都不知道从哪里开始编辑它。在这个过程中使用的while循环在哪里?只是想了解一切。谢谢。这里的for循环和你的while循环做同样的事情,在txt文件的所有行中循环。while循环在哪里使用?只是想了解一切。谢谢。@JohnFinger:好的,现在检查一下。还有ref-有没有更简单的方法将我在问题中编辑的for循环更改为while循环?我感谢你的帮助,但答案有点太复杂了,我还不明白。再次感谢。感谢您的输入,我遇到的问题是while循环。在这方面,我似乎无法理解他们。不过,我理解大部分其他部分。那个链接做了一点修改
,但现在我只是在尝试运行它时不断出错。我把路径改为scores.txt,改为scores.txt,我想我应该这么做,对吗?然后我得到一个错误,没有定义f的名称。@JohnFinger我的错。忘记更改那个变量名了。确保理解您正在运行的代码,这将在以后对您有很大帮助。干杯编辑:您可能也希望在循环结束时关闭该文件,因为这样做更好!就像你说的,我看到了哈哈。谢谢。现在我得到一个错误:FileNotFoundError:[Errno 2]没有这样的文件或目录:“scores.txt”出于某种原因。@JohnFinger请确保您位于正确的目录中。如果您的脚本和scores.txt位于同一目录中,请确保检查文件名拼写是否正确,如果您不使用Windows,请注意这种情况;如果您从控制台启动Python,请确保位于scores.txt所在的目录中,以便运行程序。
Exception during Type Casting.- Input
Exception during Type Casting.- Input
Exception during Type Casting.- Input
Exception during Type Casting.- Input
Debug 4: 434
average of scores is= 86.80
#- Read file content.
with open(file_name, "rb") as fp:
content = fp.read()
#- Get all numbers from the file content by RE and map.
scores = map(int, re.findall("\d+", content))
return scores
def main():
scores = []
scores_file = open("path to scores.txt", 'r')
line_list = list(scores_files.readlines())
i = 0
while i < len(line_list):
scores.append(line_list[i])
i += 1
showscores(scores)
def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))
def main():
scores = []
scores_file = open('scores.txt', 'r')
line_list = list(scores_file.readlines())
scores_file.close()
i = 0
while i < len(line_list):
scores.append(int(line_list[i].strip()))
i += 1
showscores(scores)
main()