学习python文件操作的内容,遇到一个问题。

问题遇到的现象和发生背景

要求计算出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} 字节'
运行结果及报错内容

img


这是他的运行结果,但是我查看文件夹属性发现他有9000多字节

img


为什么会少?

我的解答思路和尝试过的方法
我想要达到的结果

你的程序在我机子上测也正确,你可以查一下每个文件的大小,比如:

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

img

两个目录不一样呀。

看你的图,路径不是一个路径的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
'''

img