开发者

Renaming file names containing spaces

开发者 https://www.devze.com 2023-04-06 08:10 出处:网络
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

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()
filename开发者_StackOverflow社区s = 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:

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(" ", "-"))
0

精彩评论

暂无评论...
验证码 换一张
取 消