Home > Net >  Python Cannot Find File Specified
Python Cannot Find File Specified

Time:04-28

I am trying to rename a file, but python cannot find the file specified.

I have a file located here:

C:\Users\my_username\Desktop\selenium_downloads\close_of_day_reports\close-of-day-2022-04-24-2022-04-23.pdf

I am trying to rename the file to test.pdf

Here is the code I am using:

import os

os.rename(
     src = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf",
     dst = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf"

)

The error message I am getting is:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf' -> 

'C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf'

What am I doing wrong?

Edit #1:

  • The original file was not deleted, it still exists.
  • It's really strange, when I run it the first time, the file does not get renamed, but when I run it again, it does.
  • Weird, for some reason it works in Python Shell, but not my Python file.

Edit #2:

I am using Selenium to download the file. When I comment the part of my code out that downloads the file from Selenium, my os.rename code works fine. Weird.

CodePudding user response:

Based off the error, I think you are still leaving one the original name or not changing the right one.

import os

os.rename(
     src = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf",
     dst = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf"

)

CodePudding user response:

I'm pretty sure you ran the code once, renamed the file, and now it won't run again because you already renamed it.

CodePudding user response:

Careful reading is your friend. Computers don't know or care what you meant:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\my_usernamer\Desktop\selenium_downloads\close_of_day_reports\close-of-day-2022-04-24-2022-04-23.pdf'

See the stray r in the path?

  • Related