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

2024-10-02 00:43:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文本文件。其中一个被称为“RoundOneWinners”,如下所示:

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

另一个名为“RoundTwoTotalScores\u entered”,如下所示:

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

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

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

^这是通过将两个文本文件中的C和C相加而形成的

问题是,我将使用什么代码来打开这两个文本文件,能够将代码取出,然后将它们添加到一起。很抱歉,我没有任何示例代码,我不知道从哪里开始,因为我在这方面非常新


Tags: 代码示例字母文本文件enteredroundonewinnersroundtwototalscores
2条回答

你可以试试这个。请记住,您需要确定文件的读写位置。你知道吗

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

一个简单的答案:

# 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))))

相关问题 更多 >

    热门问题