Search code examples
pythonunixdictionaryls

Python script to sum values from ls -l output


From other post I could read the output of ls -l and filter only Bytes of files in a dir. But, I also want to put all those values into a list (array) and then get the total sum of elements.

I tried to create a list b and then print only the sum(b). But, when I want to create a list, I get MemoryError.

Situation Now:

import subprocess
import csv
process = subprocess.Popen(['ls', '-l',], stdout=subprocess.PIPE)
stdout, stderr = process.communicate()

reader = csv.DictReader(stdout.decode('ascii').splitlines(), delimiter = ' ', skipinitialspace=True, fieldnames= ['Owner','Date','Dir','Priv','Bytes','Field2', 'Field3', 'Field4', 'Field5'])

Issues start here

for row in reader:
    a = row['Bytes']
    b = [int(a)]
    for i in b:
        b.append(i)
    continue
    print(b)

OUTPUT:

Traceback (most recent call last):
  File "script2.py", line 13, in <module>
    b.append(i)
MemoryError

Any help how to put into one list all elements and then get sum would be very appreciated. Thanks!


Solution

  • You are iterating over b list and adding its elements to it, it will never stop.

    for i in b:
        #b.append(i) #This is the problem
        #continue #Go to the next iteration
        print(i)
    

    Edit:

    for row in reader:
        a = row['Bytes']
        print(a)
        b.append(int(a))