2

I have a folder full of pdf files. I'm trying to remove all the spaces from files name and replace them with underscores. Here's what I have so far:

import os, sys

folder = path to folder
FileList = os.listdir(folder)

for files in FileList:
    if ' ' in files:
        NewName = files.replace(" ", "_")
        os.rename(files, NewName)

When I run this script I get the following error:

WindowsError: [Error 2] The system cannot find the file specified

I'm guessing there is a pretty simple fix, but I've look all over and cannot find a solution for the life of me.

Thanks for the help!

1
  • cwd/folder/file cannot be found in cwd/file. Commented Jan 15, 2016 at 22:11

4 Answers 4

8

...

os.rename(os.path.join(folder, files), os.path.join(folder, NewName))
Sign up to request clarification or add additional context in comments.

Comments

2

just change your directory to the one in which the files has to be renamed and then follow your code.

use: os.chdir("destinationFolder").

Comments

1

I found a simple solution for my case. I was wanting to rename files and kept getting the WindowsError: [Error 2]. Simply changing the current directory with

os.chdir(currdir)

and then not trying to work with the full path did the trick. Here's the relevant lines of script

if(os.path.exists(wd)) == 0:
print(wd+" DOES NOT EXIST!!")
sys.exit()

directories = [x[0] for x in os.walk(wd)]
ld = len(directories)
dsorted = sorted(directories)
print(dsorted)

for num in range(1,ld):
    currdir = dsorted[num]
    print("Working on Directory  "+currdir)
    os.chdir(currdir)
    filenames = next(os.walk(currdir))[2]
    l = len(filenames)

    for num in range(0,l):

        name = filenames[num]
        print("Present file  "+name)
        modtime = os.path.getmtime(name);print(modtime)
        moddate =datetime.datetime.fromtimestamp(modtime).strftime('%Y %m %d')
        moddate = moddate.replace(" ", "")
        print(moddate)

        namesplit = name.split(".")

        base = namesplit[0]
        newbase = base+"_"+moddate   
        newname = newbase+"."+namesplit[1]
        print(newname)       

        os.rename(name,newname)
        input()

Comments

0

You renaming files in current directory but reading in the folder. You need to add to os.rename the folder path or at the beginning os.chdir(folder) and then just use os.listdir() and os.rename

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.