2

I am trying to move specific folders within a file directory inside a flash drive with the Python shutil library. I am getting the following error:

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

I have looked at some questions posted and I think my issue may be that I am not declaring the filepath correctly. I am using the Spyder app for Python and Windows 10.

import shutil
shutil.move('D:\\New Folder\CN00020', 'D:\\Batch Upload')
darthbith
  • 18,484
  • 9
  • 60
  • 76

1 Answers1

4

the problem is that \ has special meaning. Python interprets \C as a special character. There are three solutions:

# 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')
Justus
  • 56
  • 2
  • windows filesystem APIs have supported forward slashes for decades (with Win32 I think), it's nothing to do with `shutil` – Sam Mason Jul 30 '19 at 15:47
  • @SamMason That's not totally true, see https://stackoverflow.com/a/31736631/2449192. But by-and-large, that's correct :-) – darthbith Jul 30 '19 at 20:23
  • @darthbith that's why I said the APIs, not windows generally... when you're using `shutil.move` you're basically calling [`os.rename`](https://github.com/python/cpython/blob/c4cacc8c5eab50db8da3140353596f38a01115ca/Modules/posixmodule.c#L4133) which under windows calls [`MoveFileExA`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexa) which is documented to [convert "/" to "\" as part of converting the name to an NT-style name](https://learn.microsoft.com/en-gb/windows/win32/fileio/naming-a-file#maximum-path-length-limitation) on local drives like here – Sam Mason Jul 31 '19 at 10:26