1
votes

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!

4
cwd/folder/file cannot be found in cwd/file. - Łukasz Rogalski

4 Answers

5
votes

...

os.rename(os.path.join(folder, files), os.path.join(folder, NewName))
2
votes

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

use: os.chdir("destinationFolder").

1
votes

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()
0
votes

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