如何从文本文件中添加数字

时间:2017-09-25 21:54:54

标签: python text-files

我有两个文本文件。一个被称为'RoundOneWinners',看起来像这样:

C,18
D,22
F,25
E,26

另一个名为'RoundTwoTotalScores_entered',看起来像这样:

C, 9
D, 15
F, 21
E, 27

我需要做的是在每个文本文件中添加相应的字母,然后将它们保存到新的文本文件中。 未来的文本文件应如下所示:

C, 27
D, 37
F, 46
E, 53

^这些是通过将两个文本文件等中的C和C加在一起而制作的。

问题是,我将用什么代码打开两个文本文件,能够获取代码然后将它们一起添加。对不起,我没有任何示例代码,我不知道从哪里开始,因为我是非常新的

2 个答案:

答案 0 :(得分:0)

你可以试试这个。请记住,您需要确定文件的读取和写入位置。

import sys

f1d = {}
lines = open('/path/to/your/file1.csv')
for l in lines:
    sl = l.split(',')
    f1d[sl[0]] = int(sl[1])
lines.close()

f2d = {}
lines2 = open('/path/to/your/file2.csv')
for l in lines2:
    sl = l.split(',')
    f2d[sl[0]] = int(sl[1])
lines2.close()

output = ''
for k,v in f1d.iteritems():
    output += k + ',' + str(f1d[k] + f2d[k]) + '\n'

f = open('/path/to/your/file.csv', 'w')
f.write(output)
f.close()

答案 1 :(得分:0)

一个简单的答案:

# assuming the order of the results is important, we us an OrderedDict
from collections import OrderedDict
totals = OrderedDict()

# open the file
with open('RoundOneWinners.txt','r') as f:
    # loop over the rows
    for row in f:
        # split the row into letter and number
        letter, number = row.split(',')

        # try to add the number to the entry in totals.
        try:
            totals[letter] += int(number)
        except KeyError:
            # we could not find the letter in totals yet, so just set the value
            totals[letter] = int(number)

# same thing, second file
with open('RoundTwoTotalScores_entered.txt','r') as f:
    for row in f:
        letter, number = row.split(',')
        try:
            totals[letter] += int(number)
        except KeyError:
            totals[letter] = int(number)

# loop over your dictionary and write the results
with open('result.txt', "w") as f:
    for letter, total in totals.iteritems():
        f.write(",".join((letter, str(total))))