I want to rename an mp3 file.
os.rename(f'C:\\Users\\axeld\\Desktop\\Music\\NG Trial\\{item}',
f'C:\\Users\\axeld\\Desktop\\Music\\NG Trial\\{Song_name}')
But I get this error:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\axeld\\Desktop\\Music\\NG Trial\\109650.mp3' -> 'C:\\Users\\axeld\\Desktop\\Music\\NG Trial\\Operation: Evolution.mp3'
I am a 100% sure that the file is there, so why am I getting this error?
I don't have a Windows box to try this on, but have you considered using os.path.join
to create paths?
basedir = os.path.join('C:/', 'Users', 'axeld', 'Desktop', 'Music', 'NG Trial')
old_name = os.path.join(basedir, item)
new_name = os.path.join(basedir, song_name)
os.rename(old_name, new_name)
From the documentation of os.path.join:
Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.
Notice the very last line, which documents a special case on Windows (see also this answer on SO: that's why there's forward-slash after C:
in my code above.
Based on the comments, the os.path.join
solution would still incur in errors.
As a workaround, you can use raw strings:
os.rename(
r'C:\Users\axeld\Desktop\Music\NG Trial\{}'.format(item),
r'C:\Users\axeld\Desktop\Music\NG Trial\{}'.format(song_name))