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
just change your directory to the one in which the files has to be renamed and then follow your code.
use: os.chdir("destinationFolder").
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
...
os.rename(os.path.join(folder, files), os.path.join(folder, NewName))
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()