Python - Reading comma-separated values ​​from a text file, then outputting the result to a text file

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

at

file.txt

1,2,3

4,5,6

7,8,9

So far I have a simple code

x = 1
y = 2
z = 3

sum=x+y+z

print(sum)

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

I would like it to iterate over each line in a text file, this would be with a simple loop.

However, I also do not know how I will output the results to another text file. i.e. answer.txt

6

fifteen

24

Many thanks.

+3
source share
6 answers

Welcome to StackOverflow!

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

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

: text.txt answer.txt.

"", , , , .

"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", "answer.txt" .

filestreamtwo.write(total)

"answer.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)
+7

, , :

out = file('answers.txt', 'w')
for line in file('file.txt', 'r'):
    s = 0
    for num in line.strip().split(','):
        s += int(num)
    out.write("%d\n" % s)
0

, (input() raw_input() Python 2) ( print()).

script:

python script.py < file.txt > answer.txt

(Python 2.7):

while (True):
    try:
        x, y, z = [int(val) for val in raw_input().split(',')]
        print (x + y + z)
    except EOFError:
        pass
0

, , , ".csv". :

csv CSV, : http://docs.python.org/2/library/csv.html

:

with open('test.csv','rb') as csvfile:
    csvreader = csv.reader(csvfile)
    output_fil = open('output.txt', 'ab')
    for row in csvreader:
        result = 0
        for elem in row:
            result = result + int(elem)
        print result
        output_fil.writelines(str(result))

text.csv :

1,2,3
4,5,6
...

output.txt :

6
15
..
0
INFILE = "input.csv"
OUTFILE = "my.txt"

def row_sum(row, delim=","):
    try:
        return sum(int(i) for i in row.split(delim))
    except ValueError:
        return ""

with open(INFILE) as inf, open(OUTFILE, "w") as outf:
    outf.write("\n".join(str(row_sum(row)) for row in inf))
0
source
with open("file2.txt","w") as f:
    print >> f,"\n".join(map(lambda x:str(sum(int(y) for y in x.split(","))),open("file1.txt")))
-1
source

All Articles