Renaming file names containing spaces

19,082

Solution 1

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(' ', '-')))
...
>>>

Solution 2

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(" ", "-"))
Share:
19,082
igniteflow
Author by

igniteflow

Python/Django developer, interested in the internets, big data and fail videos

Updated on June 22, 2022

Comments

  • igniteflow
    igniteflow about 2 years

    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?

  • tripleee
    tripleee almost 13 years
    +1 The actual error is that you are not passing a list of arguments to os.path.join -- you concatenate a literal string with +, instead of passing a comma-separated list -- but since this is redundant, just take it out.