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?
Avoid spacesSpaces are not supported by all operating systems or by command line applications. A space in a filename can cause errors when loading a file or when transferring files between computers. Common replacements for spaces in a filenames are dashes (-) or underscores (_).
The safest and quickest way to rename your files and replace spaces in filenames with underscores is to use Easy File Renamer. EFR lets you add multiple folders at a time, to batch rename files from different folders. It saves a lot of your time.
You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.
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:
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 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(' ', '-')))
...
>>>
If you are already in the directory which contains the files you want to rename, you don't need to give absolute path:
for filename in filenames:
os.rename(filename, filename.replace(" ", "-"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With