根据代码执行结果,源文件路径 E:\Python\CISDI\news_policy_download_attachment/temp\附件3.doc
不存在。请按以下步骤排查:
🔍 问题诊断与解决方案
路径验证
# 验证路径是否存在 import os print(os.path.exists(r'E:\Python\CISDI\news_policy_download_attachment/temp\附件3.doc'))
- 返回
False
说明路径错误或文件不存在
- 返回
路径格式修正
- 统一使用反斜杠
\\
或原始字符串:# 推荐写法 source_file = r'E:\\Python\\CISDI\\news_policy_download_attachment\\temp\\附件3.doc'
- 统一使用反斜杠
文件存在性检查
- 在资源管理器手动导航到该路径
- 检查文件名是否包含隐藏扩展名(如
附件3.doc.doc
)
✅ 正确实现代码
import os
import shutil
# 使用原始字符串避免转义问题
source = r'E:\Python\CISDI\news_policy_download_attachment\temp\附件3.doc'
target_dir = r'E:\目标文件夹'
# 验证并修复路径
if not os.path.exists(source):
print(f"错误:源文件不存在 - {source}")
exit(1)
# 获取纯文件名
file_name = os.path.basename(source)
target_path = os.path.join(target_dir, file_name)
# 创建目标目录(如果不存在)
os.makedirs(target_dir, exist_ok=True)
# 执行复制操作
try:
shutil.copy2(source, target_path)
print(f"文件已成功复制到:{target_path}")
except PermissionError:
print("错误:权限不足,请检查目标文件夹权限")
except Exception as e:
print(f"复制失败:{str(e)}")
📝 关键改进点
路径处理优化
- 使用
os.path.join
确保路径兼容性 - 原始字符串避免
\t
等转义字符问题
- 使用
错误处理增强
- 明确区分文件不存在、权限错误等异常类型
- 目标目录自动创建功能
跨平台支持
- 代码可在Windows/Linux/macOS通用
- 路径分隔符自动适配
💡 使用建议
路径获取技巧
# 拖拽文件到终端获取绝对路径 print("请拖拽文件到此处:") file_path = input().strip()
批量处理扩展
# 复制整个文件夹 shutil.copytree('源文件夹', '目标文件夹')
进度监控
# 大文件复制进度 def copy_with_progress(src, dst): total = os.path.getsize(src) copied = 0 with open(src, 'rb') as fsrc: with open(dst, 'wb') as fdst: while True: buf = fsrc.read(1024*1024) # 1MB缓冲区 if not buf: break fdst.write(buf) copied += len(buf) print(f"进度:{copied/total*100:.1f}%")
请根据实际情况调整源文件路径和目标路径,确保:
- 源文件真实存在
- 目标磁盘有足够空间
- 程序有文件操作权限