I'm trying to rename some files, but getting a baffling error*. When I run this:

if os.path.isfile(fullPath):
    print 'fmf exists'
    print fullPath
    print newFilePath

I get the following error:

fmf exists
(correct fullPath)
(correct newFilePath, ie. destination)
Traceback (most recent call last):
  File "", line 374, in ?
OSError: [Errno 2] No such file or directory

Since I know that the file at fullPath exists, I'm baffled by the error. Of course, newFilePath doesn't exist, because that would be dumb. Any hints?

Thanks! Alex

*Aren't they all?

Was it helpful?


You can still get the exception if you try to copy to a directory that does not exist.


I can't see the full inner workings of your code, so here's my two cents worth:

Your newFilePath may contain a directory that doesn't exist. If that is the case, then depending on your operating system, your program is unable to create a file in a directory that doesn't exist. That could be your error.

Hope this helps

It seems like the poster solved his problem, but I had the same symptom and the cause appeared to be different. The file I was trying to rename had just been created in a subprocess call on the previous line. If I ran my script again, I didn't have the rename problem, since the file had been created in the previous run, but if I deleted the file previously created, I would get the same problem with rename. It seems like os.rename was getting called before the subprocess was completed and the file to be renamed therefore didn't exist yet. I inserted an os.wait() after the subprocess call, and I believe that this has solved my problem.

I had the same error when my new filename contained forward slashes, which are confused with directory separators in Unix and Linux. For example, renaming a file to "4/27/2015.txt" leads to a directory that doesn't exist and results in "No such file or directory". You can solve this by replacing the forward slashes with any other acceptable character.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow