python读取文件中的内容并输出,Python-从文本文件读取逗号分隔的值,然后将结果输出到文本文件...

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

in

file.txt

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)

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.

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

i.e. answers.txt

6

15

24

Many thanks.

解决方案

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:

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

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

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

for line in filestream:

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(",")

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"

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!

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

filestreamtwo.write(total)

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

Here's the code again:

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读取文件中的内容并输出,Python-从文本文件读取逗号分隔的值,然后将结果输出到文本文件...)