Rename 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 a hyphen. I have the following which breaks down 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 an 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?

+6
source share
2 answers

I think that just because you have the wrong syntax in your os.path.join call, the elements you connect should be represented as two different arguments, separated by commas. 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(' ', '-'))) ... >>> 
+19
source

If you are already in a directory that contains the files you want to rename, you do not need to specify an absolute path:

 for filename in filenames: os.rename(filename, filename.replace(" ", "-")) 
+8
source

Source: https://habr.com/ru/post/897598/


All Articles