gpt4 book ai didi

python - OSError : [WinError 123] The filename, 目录名或卷标语法不正确:[Python]

转载 作者:太空宇宙 更新时间:2023-11-03 19:41:59 25 4
gpt4 key购买 nike

我想重命名 mp3 文件。

   os.rename(f'C:\\Users\\axeld\\Desktop\\Music\\NG  Trial\\{item}',
f'C:\\Users\\axeld\\Desktop\\Music\\NG Trial\\{Song_name}')

但我收到此错误:

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'

我 100% 确定该文件存在,那么为什么我会收到此错误?

最佳答案

我没有 Windows 机器来尝试此操作,但您是否考虑过使用 os.path.join 来创建路径?

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)

来自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.

请注意最后一行,它记录了 Windows 上的一个特殊情况(另请参阅 answer on SO :这就是为什么在上面的代码中 C: 之后有正斜杠。

替代解决方案

根据评论,os.path.join 解决方案仍然会出现错误。作为解决方法,您可以使用原始字符串:

os.rename(
r'C:\Users\axeld\Desktop\Music\NG Trial\{}'.format(item),
r'C:\Users\axeld\Desktop\Music\NG Trial\{}'.format(song_name))

关于python - OSError : [WinError 123] The filename, 目录名或卷标语法不正确:[Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60369372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com