如何对文件中的值求和并使用 python 中的新值更新文件

How to sum values in a file and update the file with the new values in python

假设我有一个包含这样数据的文件:

Bicycle,204,28,271,193
Bicycle,136,190,79,109

我想把数字相加,这样新的行就会像那样

Bicycle,204,28,475,221 #as 271+204=475 and 28+193=221
Bicycle,136,190,215,229 #as 136+79=215 and 190+190=229

等等 我该怎么做 请注意,我试图像这样拆分数字:

    with open(filepath) as f:
        matrix=[line.split(',') for line in f]
        f.close()
    print(matrix[0])

所以当我打印矩阵时,它会给我这个输出

['Bicycle', '204', '28', '271', '193\n']

那么如何对数字求和并修改我的文件以获得新数字?

with open("bike.txt") as f:
    matrix=[line.strip().split(',') for line in f] #add strip to get rid of '\n'
    f.close()
newMatrix = [] #setup the new Matrix you'll want to use
for each in matrix:#iterate the initial matrix you took from the txt file
    myMatrix = []#new lines that will be added to the newMatrix
    myMatrix.append(each.pop(0))#first item that will be kept as a string
    addThis = 0 #variable for adding the values
    for rest in each:#for everything left after removing the first string
        addThis += int(rest) # convert to integer and add to the sum value
    myMatrix.append(addThis) # add that summed value to the new line cell
    newMatrix.append(myMatrix) #add that line to the total matrix
print(newMatrix[0]) #test that it works
# your default code that reads in the csv
with open(filepath) as f:
    matrix=[line.split(',') for line in f]
    
    f.close()

# 'w' means to write over the file and its existing content
with open(filepath, 'w') as f:
    # loop over each row in your matrix
    for row in matrix:
        # add 2nd position value in list to 4th
        row[3] = int(row[1]) + int(row[3])

        # values are read in as string, and last value can contain linebreak
        row[4] = row[4].replace('\n', '')
        # add 2nd position value in list to 4th
        row[4] = int(row[2]) + int(row[4])

        # turn values back into string
        row = [str(val) for val in row]
        # concatenate into comma separated string
        row = ','.join(row)
        # write to file
        f.write('{}\n'.format(row))

    f.close()

如果您使用上下文管理器打开文件,with,它会在缩进块结束时自动关闭,所以不要关闭它!

为了读取和写入同一个文件,您可以制作一个 单个 描述符,同时启用两个功能,open("path", "r+") doc, or the fileinput module doc; here you can find more examples ex.

基本方法如下:

path = 'my_file' # your path
# read
text = ''
with open(path, 'r') as fd:
   text += fd.read()

# process
new_text = ''
for line in text.splitlines():
    bike, term1, term2, term3, term4 = line.split(',')

    # new relationships
    new_term3 = f'{int(term1) + int(term3)}'
    new_term4 = f'{int(term2) + int(term4)}'

    # update result
    new_text += ','.join((bike, term1, term2, new_term3, new_term4)) + '\n'

# save
with open(path, 'w') as fd:
   fd.write(new_text)