2 回答

TA贡献1998条经验 获得超6个赞
“对文件的内容求和”到底是什么意思?您是否将名为“lab3.txt”的文件中的所有数字相加?
要将文件的内容存储在变量中,您可以使用myfile.readlines(). (不是myfile.readlines--括号是必需的。如果您不使用括号,则该语句不会读取任何内容。)或者使用for块一次一行地遍历文件的内容。但不是两者,正如 ShadowRanger 的评论所解释的那样。
假设“lab3.txt”包含以下几行。
84
236
956
31
163
538
4
861
要找到它们的总和,您可以执行以下操作。
ctn = 0
myfile = open('lab3.txt')
for item in myfile:
ctn += int(item) # convert string to integer
print(ctn)
在这里,item将依次获取文件中每一行的(字符串)值。它被转换为整数并添加到ctn.
readlines返回一个列表。(该列表的每个元素都是一个字符串,字符串是文件中的行。)如果必须使用readlines,则必须将列表中的元素转换为整数。
myfile = open('lab3.txt')
lines = myfile.readlines()
lines_int = [int(item) for item in lines]
ctn = sum(lines_int)
print(ctn)
不要忘记关闭文件。
myfile.close()
close如果您使用文件上下文,则不必为此烦恼。观察如何将代码减少到两行。
with open('lab3.txt') as myfile:
ctn = sum([int(item) for item in myfile.readlines()])

TA贡献1874条经验 获得超12个赞
您的项目未在您的代码中声明为 int。尝试解析它。
int ctn = 0
myfile = open("lab3.txt")
lines = myfile.readlines
for item in myfile:
ctn += int(item)
print(ctn)
添加回答
举报