要求计算出source目录里面(不包含子目录)所有的文件的大小之和。
import os
from os.path import isfile, join
targetDir = 'C:\source'
totalsize = 0
for f in os.listdir(targetDir):
filePath = join(targetDir, f)
if isfile(filePath):
totalsize += os.path.getsize(filePath)
print(f'合计大小为 {totalsize} 字节')
你的程序在我机子上测也正确,你可以查一下每个文件的大小,比如:
import os
from os.path import isfile, join
targetDir = r'c:\source'
totalsize = 0
for f in os.listdir(targetDir):
filePath = join(targetDir, f)
if isfile(filePath):
tmp = os.path.getsize(filePath)
print(filePath, f"其大小为:{tmp}")
totalsize += tmp
print(f'合计大小为 {totalsize} 字节')
C:\source
两个目录不一样呀。
看你的图,路径不是一个路径的source
import os
cou = 0
for i in os.listdir(dirname):
file = dirname + "\\" + i
if os.path.isfile(file):
print(file)
cou += os.path.getsize(file)
print(f"总大小:{cou}")
'''--result
D:\Soft\testData\test\aaa.xlsm
D:\Soft\testData\test\BP.txt
D:\Soft\testData\test\c2.txt
D:\Soft\testData\test\Label.txt
D:\Soft\testData\test\test1.xml
D:\Soft\testData\test\test2.xml
D:\Soft\testData\test\无标题.png
总大小:154223
'''