Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming file names containing spaces

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?

like image 379
igniteflow Avatar asked Sep 19 '11 10:09

igniteflow


People also ask

Can a file name include spaces?

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 (_).

How do you replace spaces with underscores in a file name?

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.

How do I rename files in bulk with different names?

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.


2 Answers

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(' ', '-')))
...
>>>
like image 149
Max Spencer Avatar answered Oct 21 '22 02:10

Max Spencer


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(" ", "-"))
like image 44
infrared Avatar answered Oct 21 '22 01:10

infrared