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

Windows11下用Python的shutil和os移动文件报错,求解决方法

问题修复方案

核心错误分析

  • 字符串未终止错误:你在原始字符串(r开头)末尾加了反斜杠,这会导致反斜杠转义闭合的引号,使Python无法识别字符串的结束位置,引发语法错误。
  • 无效目录错误:os.listdir()需要传入文件夹路径,但你传入的是具体文件路径(AI.jpg),因此会报错“不是有效目录”。
  • 函数使用偏差:你描述的需求是“移动”文件,但代码使用的是shutil.copy(仅复制文件),若需移动应改用shutil.move。

修正后的代码

import shutil 
import os 

# 源文件路径:去掉末尾反斜杠,指向具体文件
source = r"C:\Users\zaner\Downloads\AI.jpg"
# 源文件夹路径:用于os.listdir查看下载目录内容
source_dir = r"C:\Users\zaner\Downloads"

print("Before Operation: ")
print(os.listdir(source_dir))  # 传入文件夹路径而非文件路径
perm = os.stat(source).st_mode
print("File Permission mode:", perm, "\n")

# 目标文件夹路径:去掉末尾反斜杠
destination = r"C:\Users\zaner\OneDrive\Pictures\Camera Roll"

# 确保目标文件夹存在,避免因文件夹不存在报错
if not os.path.exists(destination):
    os.makedirs(destination)

# 移动文件用shutil.move,复制文件用shutil.copy,按需选择
dest = shutil.move(source, destination)
# 若需复制则替换为:dest = shutil.copy(source, destination)

print("Operation completed successfully, file saved to:", dest)

额外注意事项

  • Windows路径使用原始字符串(r开头)时,不要在末尾加反斜杠,否则会破坏字符串的闭合引号;若必须保留末尾反斜杠(比如指向文件夹),可写成r"C:\xxx\\"或者"C:\\xxx\\"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:40:04