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

Time:04-20

let's say i have a file with data like that:

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

I want to add the numbers with each other so that the new lines will be like that

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

and so on so how can i do that note I tried to split the numbers like that:

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

so when I print matrix it gives me this output

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

so how can I sum the numbers and modify my file to have the new numbers?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

If you open a file using a context manager, with, it will automatically close at the end of the indentation block, so don't close it!

For reading and writing to the same file you could either make a single descriptor with both features enables, open("path", "r ") doc, or the fileinput module doc; here you can find more examples ex.

Here a basic approach:

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)
  • Related