本文介绍如何修改 python 文件移动脚本,将原本仅支持 `startswith()` 和 `endswith()` 的精确边界匹配,升级为支持子字符串“包含匹配”(即类似通配符 `*356333*` 的模糊查找),提升对合同号、客户编号等非固定位置标识的检索能力。
在实际文件管理场景中,用户常需根据嵌入在文件名中间的编号(如 Invoice_2025_356333_Final.pdf 或 Contract-356333-Draft.docx)批量移动文件。此时,str.startswith() 和 str.endswith() 无法满足需求——它们仅能匹配开头或结尾,而真正的业务关键词往往“藏在中间”。
幸运的是,Python 提供了更灵活、更直观的成员运算符 in,可直接判断子字符串是否出现在文件名任意位置,无需额外导入模块或复杂正则表达式。只需将原脚本中:
if entry.startswith(filename_match):
替换为:
if filename_match in entry:
即可实现“包含匹配”。完整优化后的核心逻辑如下:
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
m
oveto_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.")✅ 关键改进说明:
⚠️ 注意事项:
该方案简洁、健壮、符合 Pythonic 风格,是日常自动化文件归档任务的理想基础。