How to read comma separated values from a text file, then output result to a text file?
csv, loops, python
Solution
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 indented 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 each element in `currentline` with the `int` function around. 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)
Problem
I need to create a program that will add numbers read from a text file separated by commas. i.e. 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` and `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 ```