首页 > 解决方案 > 使用 python shutil 库移动文件

问题描述

我正在尝试使用 Pythonshutil库在闪存驱动器内的文件目录中移动特定文件夹。我收到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'D:\\New Folder\\CN00020'. 

我查看了一些发布的问题,我认为我的问题可能是我没有正确声明文件路径。我正在使用适用于 Python 和 Windows 10 的 Spyder 应用程序。

import shutil
shutil.move('D:\\New Folder\CN00020', 'D:\\Batch Upload')

标签: python

解决方案


问题是它\具有特殊含义。Python 解释\C为特殊字符。有三种解决方案:

# escape backspace
shutil.move('D:\\New Folder\\CN00020', 'D:\\Batch Upload')

# use raw strings
shutil.move(r'D:\New Folder\CN00020', r'D:\Batch Upload')

# use forward slashes which shutil happens to support
shutil.move('D:/New Folder/CN00020', 'D:/Batch Upload')

推荐阅读