You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python获取目录及文件大小信息输出结果异常如何修复

代码问题修复

原有代码问题梳理

  • 缺少pathlib模块的Path类导入,直接调用Path.cwd()会触发未定义报错
  • 全局共用totalSize变量累加所有文件大小,无法单独展示单个文件的体积
  • 目录说明的打印语句放在了文件遍历循环内部,每遍历一个文件就重复打印一次目录提示
  • 固定写死打印catnames.txt/dognames.txt的文件名,和实际遍历到的文件不匹配
  • 部分路径未使用原始字符串前缀,Windows路径的反斜杠可能被识别为转义字符导致报错
  • 大小赋值语句换行未处理,会触发语法报错

修复后完整代码

import os
from pathlib import Path

# 打印工作目录切换信息
print("当前初始工作目录:", Path.cwd())
os.chdir(r'C:\cpt180Stuff')
print("切换后工作目录:", Path.cwd())

# 打印各级目录文件列表
print("The CPT180Stuff folder contains the following: " + str(os.listdir(r'C:\cpt180stuff')))
print("The CPT180Stuff\cars folder contains the following: " + str(os.listdir(r'C:\cpt180stuff\cars')))
print("The CPT180Stuff\pets folder contains the following: " + str(os.listdir(r'C:\cpt180stuff\pets')))

# 打印cats目录下各文件大小
print("\nThe CPT180Stuff\pets\cats folder contains the following files with size: ")
cat_dir = r'C:\cpt180stuff\pets\cats'
for filename in os.listdir(cat_dir):
    file_path = os.path.join(cat_dir, filename)
    file_size = os.path.getsize(file_path)
    print(f"{filename}: {file_size} bytes")

# 打印dogs目录下各文件大小
print("\nThe CPT180Stuff\pets\dogs folder contains the following files with size: ")
dog_dir = r'C:\cpt180stuff\pets\dogs'
for filename in os.listdir(dog_dir):
    file_path = os.path.join(dog_dir, filename)
    file_size = os.path.getsize(file_path)
    print(f"{filename}: {file_size} bytes")

修复说明

  • 新增Path类导入,解决未定义报错
  • 取消全局累加逻辑,每个文件单独计算体积后直接输出,自动匹配实际遍历到的文件名
  • 将目录说明打印语句移到循环外部,每个目录仅打印一次提示
  • 所有Windows路径添加原始字符串前缀r,避免转义字符异常
  • 使用f-string格式化输出,自动拼接文件名、大小和bytes单位,完全符合需求

内容的提问来源于stack exchange,提问作者RollietheGoalie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:39:03