欢迎来到StackOverflow!
你的想法是对的,让我们先打开一些文件。with open("text.txt", "r") as filestream:
with open("answers.txt", "w") as filestreamtwo:
在这里,我们打开了两个文件流“text.txt”和“answers.txt”。
由于我们使用了“with”,这些文件流将在下面空白的代码运行完后自动关闭。
现在,让我们逐行运行文件“text.txt”。for line in filestream:
这将运行for循环并在文件末尾结束。
接下来,我们需要将输入文本更改为可以使用的内容,例如数组!currentline = line.split(",")
现在,“currentline”包含“text.txt”第一行中列出的所有整数。
让我们把这些整数加起来。total = str(int(currentline[0]) + int(currentline[1]) + int(currentline [2])) + "\n"
我们必须在“currentline”数组中的每个元素周围包装int函数。否则,我们将连接字符串,而不是添加整数!
之后,我们添加回车“\n”,以便更清楚地理解“answers.txt”。filestreamtwo.write(total)
现在,我们正在写入文件“answers.txt”。。。就这样!你完了!
下面是代码:with open("test.txt", "r") as filestream:
with open("answers.txt", "w") as filestreamtwo:
for line in filestream:
currentline = line.split(",")
total = str(int(currentline[0]) + int(currentline[1]) + int(currentline [2])) + "\n"
filestreamtwo.write(total)