Python-从文本文件读取逗号分隔的值,然后将结果输出到文本文件 [英] Python - Read comma separated values from a text file, then output result to text file

查看:1817
本文介绍了Python-从文本文件读取逗号分隔的值,然后将结果输出到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要创建一个程序,该程序将添加从用逗号分隔的文本文件中读取的数字.即

Basically I need to create a program that will add numbers read from a text file separated by commas. ie

file.txt

1,2,3

1,2,3

4,5,6

7,8,9

到目前为止,我已经获得了简单的代码

So far I have the simple code

x = 1
y = 2
z = 3

sum=x+y+z

print(sum)

我不确定如何将文本文件中的每个数字分配给x,y,z.

I'm not sure how I would assign each number in the text file to x,y,z.

我想要的是,它将遍历文本文件中的每一行,这将是一个简单的循环.

What I would like is that it will iterate through each line in the text file, this would be with a simple loop.

但是,我也不知道如何将结果输出到另一个文本文件. 即answer.txt

However I also do not know how I would then output the results to another text file. i.e. answers.txt

6

15

24

非常感谢.

推荐答案

欢迎使用StackOverflow!

Welcome to StackOverflow!

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

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)

这篇关于Python-从文本文件读取逗号分隔的值,然后将结果输出到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆