File Manager
你将构建什么
Python script 那个列表 files 通过 extension, 搜索 for files 通过 name 模式, and reports directory 大小 — mini file explorer.
学习目标
- Use os.listdir and os.path for file 操作
- 筛选 files 通过 extension using 列表 comprehensions
- Calculate file 大小使用 os.path.getsize
- 格式 directory summary report
前置要求
- File handling 基础
- 列表 and 列表 comprehensions
- os 模块
步骤
- 1
列表 files in directory
导入 os and 定义 list_files(path) 那个返回所有 files in given directory. Use os.listdir and 筛选到 files 仅 (不 subdirectories).
代码import os def list_files(path='.'): entries = os.listdir(path) files = [f for f in entries if os.path.isfile(os.path.join(path, f))] return sorted(files)预期结果
list_files('.') 返回排序列表的 file names in current directory.
- 2
筛选通过 extension
定义 files_by_extension(path, ext) 那个返回 files matching given extension. Use 列表 comprehension 使用 str.endswith.
代码def files_by_extension(path='.', ext='.py'): files = list_files(path) return [f for f in files if f.endswith(ext)]预期结果
files_by_extension('.', '.py') 返回所有 Python files in current directory.
- 3
Report directory 大小
定义 directory_report(path) 那个列表每个 file 使用它的大小 in 字节, 排序通过大小 (largest 首先). Print 格式化表.
代码def directory_report(path='.'): files = list_files(path) sizes = [] for f in files: full_path = os.path.join(path, f) size = os.path.getsize(full_path) sizes.append((f, size)) sizes.sort(key=lambda x: x[1], reverse=True) print(f"{'File':<30} {'Size (bytes)':>15}") print('-' * 45) for name, size in sizes: print(f"{name:<30} {size:>15}")预期结果
格式化表 的 files 排序通过大小, largest 首先.
- 4
添加输入验证与异常处理
在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。
代码def safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)预期结果
非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。
- 5
编写单元测试
使用 unittest 或 assert 语句为核心函数编写测试,覆盖正常路径、边界值和异常情况。测试是保证代码质量的安全网。
代码import unittest class TestCoreFunc(unittest.TestCase): def test_normal(self): self.assertEqual(core_func(5), expected_5) def test_boundary(self): self.assertEqual(core_func(0), expected_0) def test_exception(self): with self.assertRaises(ValueError): core_func(-1) if __name__ == "__main__": unittest.main()预期结果
运行 python test.py 后输出 OK,三个测试用例全部通过。
自己动手试试
import os
# TODO: define list_files, files_by_extension, and directory_report
# Then test with: directory_report('.')
import os
def list_files(path='.'):
entries = os.listdir(path)
files = [f for f in entries if os.path.isfile(os.path.join(path, f))]
return sorted(files)
def files_by_extension(path='.', ext='.py'):
files = list_files(path)
return [f for f in files if f.endswith(ext)]
def directory_report(path='.'):
files = list_files(path)
sizes = []
for f in files:
full_path = os.path.join(path, f)
size = os.path.getsize(full_path)
sizes.append((f, size))
sizes.sort(key=lambda x: x[1], reverse=True)
print(f"{'File':<30} {'Size (bytes)':>15}")
print('-' * 45)
for name, size in sizes:
print(f"{name:<30} {size:>15}")
directory_report('.')你学到了什么
你 used os 模块到 interact 使用 filesystem, 筛选使用 comprehensions, and 格式化 tabular 输出 — skills used in 构建 scripts, log tools, and file utilities.
相关资源
相关课程
- File Handling
File and directory 操作.
- 列表 Comprehensions
筛选 files.
相关练习
- 列表 Comprehension 测验
练习 comprehensions.
- Fill: File 模式
File 打开模式.
相关速查表
- Python Cheatsheet
os 模块引用.
相关错误
- File 不找到
Missing files.
- Permission 错误
Access 拒绝.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- File 不找到
Missing files.
- Permission 错误
Access 拒绝.