robots.txt
robots.txt

Reputation: 137

Trouble renaming files to customized names

Can't rename old files located in a folder in desktop. There are three files there item.pdf,item1.pdf and item2.pdf. What I wish to do now is rename those files to new_item.pdf,new_item1.pdf and new_item2.pdf.

I tried with the below script:

import os

filepath = "/Users/WCS/Desktop/all_files/"

for item in os.listdir(filepath):
    os.rename(item,"new_name"+".pdf")

Executing the above script throws the following error. Whereas the folder address is accurate:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'item.pdf' -> 'new_name.pdf'

How can I rename these three files item.pdf,item1.pdf and item2.pdf to new_item.pdf,new_item1.pdf and new_item2.pdf from a folder?

Upvotes: 0

Views: 27

Answers (2)

han solo
han solo

Reputation: 6590

Try this:

import os
import re

filepath = "/Users/WCS/Desktop/all_files/"

for item in os.listdir(filepath):
    match = re.search(r'\d+$', item)
    endnum = ""
    if match:
      endnum = match.group()
    os.rename(os.path.join(filepath, item), os.path.join(filepath, "new_name{}.pdf".format(endnum)))

or, if you don't wanna use re

import os

filepath = "/Users/WCS/Desktop/all_files/"

for item in os.listdir(filepath):
    new_name = item.replace('item', 'new_item')
    os.rename(os.path.join(filepath, item), os.path.join(filepath, "new_name{}.pdf".format(new_name)))

Upvotes: 1

JoshG
JoshG

Reputation: 6735

You need to either specify the full path to your file in os.rename.

Something like:

for item in filepath:
    os.rename(os.path.join(filepath, item), os.path.join(filepath, "new_item.pdf"))

Or change your current working directory to the directory where the files exist:

os.chdir("/your/file/path")

and then run your code.

See also https://docs.python.org/2/library/os.html#os.rename

Upvotes: 0

Related Questions