欢迎来到 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"
我们必须将 int 函数包裹在“currentline”数组中的每个元素周围。否则,我们将连接字符串,而不是添加整数!
之后,我们添加回车“\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)