且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python-从文本文件读取逗号分隔的值,然后将结果输出到文本文件

更新时间:2022-05-02 10:07:54

欢迎使用***!

Welcome to ***!

您的想法正确,让我们从打开一些文件开始.

You have the right idea going, let's start by opening some files.

with open("text.txt", "r") as filestream:
    with open("answers.txt", "w") as filestreamtwo:

在这里,我们打开了两个文件流"text.txt"和"answers.txt".

Here, we have opened two filestreams "text.txt" and "answers.txt".

由于我们使用了"with",这些文件流将在其下方用空格隔开的代码完成运行后自动关闭.

Since we used "with", these filestreams will automatically close after the code that is whitespaced beneath them finishes running.

现在,让我们逐行浏览文件"text.txt".

Now, let's run through the file "text.txt" line by line.

for line in filestream:

这将运行一个for循环,并在文件末尾结束.

This will run a for loop and end at the end of the file.

接下来,我们需要将输入文本更改为可以使用的内容,例如数组!

Next, we need to change the input text into something we can work with, such as an array!

currentline = line.split(",")

现在,"currentline"包含"text.txt"第一行中列出的所有整数.

Now, "currentline" contains all the integers listed in the first line of "text.txt".

让我们对这些整数求和.

Let's sum up these integers.

total = str(int(currentline[0]) + int(currentline[1]) + int(currentline [2])) + "\n"

我们必须将int函数包装在当前行"数组中的每个元素周围.否则,我们将串联字符串,而不是添加整数!

We had to wrap the int function around each element in the "currentline" array. Otherwise, instead of adding the integers, we would be concatenating strings!

然后,我们添加回车符"\ n",以使"answers.txt"更清晰易懂.

Afterwards, we add the carriage return, "\n" in order to make "answers.txt" clearer to understand.

filestreamtwo.write(total)

现在,我们正在写入文件"answers.txt" ...就是这样!大功告成!

Now, we are writing to the file "answers.txt"... That's it! You're done!

这又是代码:

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)