一种方法是将它们添加到列表中,然后使用sum
sizes = []
for i in a:
dest = '/home/zurelsoft/my_files'
fullname = os.path.join(dest, i) #Get the file_full_size to calculate size
st = int(os.path.getsize(fullname))
f_size = size(st)
sizes.append(f_size)
print sum(sizes)
或者你可以有一个变量。
sum_size = 0
for i in a:
dest = '/home/zurelsoft/my_files'
fullname = os.path.join(dest, i) #Get the file_full_size to calculate size
st = int(os.path.getsize(fullname))
sum_size += size(st)
print sum_size
或者你可以把它放在字典里......
d = {}
for i in a:
dest = '/home/zurelsoft/my_files'
fullname = os.path.join(dest, i) #Get the file_full_size to calculate size
st = int(os.path.getsize(fullname))
d[i] = size(st)
获得每个尺寸:
print '\n'.join(['%s: %d' % (k, v) for k, v in d.items()])
得到总和:
print sum(d.values())
将其全部包装到一个函数中,并使用类似于Ivo van der Wijk使用的方法:
def get_file_sizes(parent_dir, files):
import os
return sum([os.path.getsize(os.path.join(parent_dir, f)) for f in files])
调用函数:
a = ['ok.py', 'hello.py']
all_sizes = get_file_sizes('/home/zurelsoft/my_files', a)