Home > Blockchain >  Attempt to sum output returns TypeError: 'long' object is not iterable
Attempt to sum output returns TypeError: 'long' object is not iterable

Time:11-11

I am attempting to sum the total file sizes of specific file types. I am able to identify all the targeted files and get the sizes in bytes but I am running into an issue when trying to sum the output. I feel like I need to convert my output to a different type to execute print(sum(file_size))

Here is the code I have currently and the outputs.

from pathlib import Path

# get file path
for path in Path('C:\Users\file\path\here').rglob('*.kml'):

# get size of file
    Path(path).stat()
    file_size =Path(path).stat().st_size
    print(file_size)

Output:

72830
109576
179554
165898
63151
193100

Process finished with exit code 0

My end goal is to have all of these outputs summed. Any help?

CodePudding user response:

You can use a generator expression and sum the results:

from pathlib import Path
print(sum(path.stat().st_size for path in Path('C:\Users\file\path\here').rglob('*.kml')))

CodePudding user response:

Add a variable to keep track of the sum, and add the file size to it in each iteration:

from pathlib import Path

total_file_size = 0
# get file path
for path in Path('C:\Users\file\path\here').rglob('*.kml'):

# get size of file
    Path(path).stat()
    file_size =Path(path).stat().st_size
    print(file_size)
    total_file_size  = file_size
print(total_file_size)
  • Related