I'm trying to rename a number of files stored within subdirectories by removing the last four characters in their basename. I normally use glob.glob()
to locate and rename files in one directory using:
import glob, os
for file in glob.glob("C:/Users/username/Desktop/Original data/" + "*.*"):
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
os.rename(file,newFile)
But now I want to repeat the above in all subdirectories. I tried using os.walk()
:
import os
for subdir, dirs, files in os.walk("C:/Users/username/Desktop/Original data/"):
for file in files:
pieces = list(os.path.splitext(file))
pieces[0] = pieces[0][:-4]
newFile = "".join(pieces)
# print "Original filename: " + file, " || New filename: " + newFile
os.rename(file,newFile)
The print
statement correctly prints the original and the new filenames that I am looking for but os.rename(file,newFile)
returns the following error:
Traceback (most recent call last):
File "<input>", line 7, in <module>
WindowsError: [Error 2] The system cannot find the file specified
How could I resolve this?