I am writing a simple Python script to rename all files in a directory to replace all spaces in the file name with hyphens. I have the following which is crashing on os.rename
import os
path = os.getcwd()
filenames = os.listdir(path)
for filename in filenames:
os.rename(os.path.join(path + filename), os.path.join(path + filename.replace(" ", "-")))
Gives the error in the console:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
OSError: [Errno 2] No such file or directory
Any ideas on why this is happening?
I think it’s just because you have the syntax wrong in your call to os.path.join, the items you’re joining should be supplied as two distinct arguments, separated by a comma. This works fine for me: