Python 对 ls -l 输出的值求和的脚本

Python script to sum values from ls -l output

从其他 post 我可以读取 ls -l 的输出并仅过滤目录中的文件字节数。但是,我也想把所有这些值放到一个列表(数组)中,然后得到元素的总和。

我尝试创建一个列表 b,然后只打印 sum(b)。但是,当我想创建一个列表时,我得到了 MemoryError。

现在情况:

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'])

问题从这里开始

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

输出:

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

任何帮助如何将所有元素放入一个列表然后求和的帮助将不胜感激。谢谢!

您正在遍历 b 列表并将其元素添加到其中,它永远不会停止。

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

编辑

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

要制作列表,您需要检查每一行的行['Bytes']是否为空,如果不是,则转换为整数。一个很好的简洁方法是使用列表理解:

list_of_sizes = [int(row['Bytes']) for row in reader if row['Bytes']]

或者,同样的事情,使用更传统的 for 循环:

list_of_sizes = []
for row in reader:
    if row['Bytes']:
        list_of_sizes.append(int(row['Bytes']))

然后,您可以使用sum函数计算总和:

total_size = sum(list_of_sizes)