
本文介绍如何修改 python 文件移动脚本,将原本仅支持 `startswith()` 和 `endswith()` 的精确边界匹配,升级为支持子字符串“包含匹配”(即类似通配符 `*356333*` 的模糊查找),提升对合同号、客户编号等非固定位置标识的检索能力。
在实际文件管理场景中,用户常需根据嵌入在文件名中间的编号(如 Invoice_2024_356333_Final.pdf 或 Contract-356333-Draft.docx)批量移动文件。此时,str.startswith() 和 str.endswith() 无法满足需求——它们仅能匹配开头或结尾,而真正的业务关键词往往“藏在中间”。
幸运的是,Python 提供了更灵活、更直观的成员运算符 in,可直接判断子字符串是否出现在文件名任意位置,无需额外导入模块或复杂正则表达式。只需将原脚本中:
if entry.startswith(filename_match):
替换为:
if filename_match in entry:
即可实现“包含匹配”。完整优化后的核心逻辑如下:
立即学习“Python免费学习笔记(深入)”;
import os
import shutil
# Step 1: Source directory
movefrom_path = input('Enter the source directory path: ').strip()
if not movefrom_path.endswith(os.sep):
movefrom_path += os.sep # Ensure trailing slash for safe path joining
# Step 2: Destination directory
moveto_path = input('Enter the destination directory path: ').strip()
if not moveto_path.endswith(os.sep):
moveto_path += os.sep
# Step 3: Create destination if missing
os.makedirs(moveto_path, exist_ok=True)
# Step 4: User input for partial match
filename_match = input('Enter substring to search for (e.g., "356333", "INV-", "draft"): ').strip()
# Step 5 & 6: Iterate and move files containing the substring
moved_count = 0
for entry in os.listdir(movefrom_path):
full_src = os.path.join(movefrom_path, entry)
if os.path.isfile(full_src) and filename_match in entry:
full_dst = os.path.join(moveto_path, entry)
shutil.move(full_src, full_dst)
print(f"✓ Moved: {entry}")
moved_count += 1
print(f"\n✅ Done. {moved_count} file(s) moved.")✅ 关键改进说明:
- 使用 os.path.join() 替代字符串拼接,避免跨平台路径分隔符问题(如 Windows \ vs Unix /);
- 添加 os.path.isfile() 判断,防止误移目录;
- 使用 exist_ok=True 避免重复创建目录报错;
- 增加计数与反馈,提升脚本可观测性;
- filename_match in entry 是大小写敏感匹配;如需忽略大小写,可改为 filename_match.lower() in entry.lower()。
⚠️ 注意事项:
- in 运算符执行的是精确子串匹配,不支持通配符(如 * 或 ?)或正则语法。若需更高级模式(如“以 INV- 开头且含 _2024”),应使用 re.search();
- 空输入(如用户直接回车)会导致 "" in entry 恒为 True,建议添加校验:if not filename_match: print("Warning: Empty search term!"); continue;
- 对于海量文件,可考虑用 pathlib.Path 提升可读性,或结合 glob 模块实现通配符匹配(如 *.356333.*)。
该方案简洁、健壮、符合 Pythonic 风格,是日常自动化文件归档任务的理想基础。










