[Python] sum the elements of different files in python

Discussão em 'Python' iniciado por Stack, Junho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have multiples files with similar names (only change the suffix). I want to sum the values of the files in a new file. For example: file energy.dat.1 contains values in matrix format, and file energy.dat.2 has the same format but another values.
    For example:
    energy.dat.1 file constains ([[1, 2], [3, 4]])
    energy.dat.2 file constains ([[0, 1], [1, 3]])

    I want to obtain another one, total_energy, which contains the result of the sum (i.e.: ([[1, 3], [4, 7]])).


    Because I have a lot of files I have done:

    for file_name in os.listdir('.'):
    if file_name[0:10] == "energy.dat":
    total_energy = total_energy +
    np.sum(
    np.loadtxt(file_name)
    )


    (Previously I defined the array total_energy with the correct dimensions.)
    Problem: the result, total_energy, is a matrix with values equals to the sum of all elements of the files (([[13, 13], [13, 13]])) instead of (([[1, 3], [4, 7]]))

    Do you have any ideas to reach the result I want?
    Thanks

    Continue reading...

Compartilhe esta Página