简体   繁体   中英

Python 3: Error while executing os.rename()

I am trying to rename files using this code:

def rename_files(src: str,dst: str, folder_name: str):
    filepath = f"temp/{src}"
    filepath = filepath.replace("/", "\\")
    cwd = os.getcwd()
    old_path = os.path.join(cwd, filepath)
    newfilepath = f"folder/{folder_name}/{dst}.pdf"
    newfilepath = newfilepath.replace("/", "\\")
    new_path = os.path.join(cwd, newfilepath)
    if os.path.exists(old_path):
        os.rename(old_path, new_path)
    else:
        print("File does not exist")

While executing it, I get the following error:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'E:\\Repos\\GitHub\\source\\t2dm\\temp\\oldfilename.pdf' -> 'E:\\Repos\\GitHub\\source\\t2dm\\folder\\subfolder\\newfilename.pdf'

The code is being executed from:

E:\Repos\GitHub\source\t2dm\

The file oldfilename.pdf exists in E:\Repos\GitHub\source\t2dm\temp\ , and folder\subfolder also exists.

What to do to resolve this?

Edit: added some more information regarding folder\subfolder .

If the new folder folder_name does not exist, os.rename won't create it.

You can do one of:

  1. use os.renames() (note the s ), instead of os.rename in that line of your code - which will create the directories for the destination if they don't already exist.

  2. use os.makedirs() to make the dir tree for the subfolders.

If you aren't creating multiple dir trees, then option (1) is ideal for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM