【问题标题】:ValueError: rename: embedded null character in dstValueError:重命名:在 dst 中嵌入空字符
【发布时间】:2019-09-04 08:12:44
【问题描述】:

我正在尝试根据元数据重命名媒体文件名。

文件名格式为song name - artist name

import os
from tinytag import TinyTag
import re

for root, dirs, files in os.walk("C:/Users/username/Desktop/Music/"):
    for name in files:
        tag = TinyTag.get(root + "\\" + name)
        if tag.artist != "":
            if name.endswith((".mp3",".m4a")):
                # try:
                file_ext = os.path.splitext(name)[-1]
                old_name = os.path.join(root, name)
                new_name = re.sub(' +', ' ', os.path.join(root, tag.title + " - " + tag.artist + file_ext))
                print(new_name)
                os.rename(old_name, new_name)
                # except:
                    # pass

除了 Prince 的 Little Red Corvette 之外,所有文件都有效:

C:/Users/username/Desktop/Music/1973 - James Blunt.mp3
C:/Users/username/Desktop/Music/Little Red Corvette  - Prince .mp3
Traceback (most recent call last):
  File "C:/Users/username/PycharmProjects/Practice/editAudioFileNames.py", line 15, in <module>
    os.rename(old_name, new_name)
ValueError: rename: embedded null character in dst

ValueError 是什么意思?我注意到在 Corvette 之后有一个额外的空间。我确实在我的代码中使用了re.sub 来修剪文件名。

暂时忽略try, except,因为代码确实可以使用它。我可以手动更改文件名,因为这是 850 首歌曲中唯一的一首,但我想知道我未来的理解。

顺便说一句,这是我第一个有用的代码!欢迎提出优化意见。

【问题讨论】:

  • 您可以使用strip 删除前导空格和尾随空格吗?更多信息在这里:programiz.com/python-programming/methods/string/strip - 谢谢
  • ValueError 是(例如)当函数需要字符串但您使用数字时。似乎new_name 的字符代码为零(空字符),并且不允许在文件名中使用。您使用roottag.titletag.artistfile_ext 创建new_name - 删除其中一个元素并查看是否获得工作代码,如果没有则删除另一个元素等。这样您可以找到元素其中有"null character"。或者您可以将ord(char)new_name 中的每个字符一起使用,以查看哪个字符具有代码zero
  • 所以我使用了你的 ord(char) 方法,它似乎在“Corvette”和“Prince”之后有一个额外的。但我不确定为什么 strip() 不删除它。在这一点上,我可能会离开它。

标签: python null-character


【解决方案1】:

请您尝试替换这些行

old_name = os.path.join(root, name)
new_name = re.sub(' +', ' ', os.path.join(root, tag.title + " - " + tag.artist + file_ext))

这些行

old_name = os.path.join(root, name.strip())
new_name = re.sub(' +', ' ', os.path.join(root, tag.title.strip() + " - " + tag.artist.strip() + file_ext.strip()))

谢谢

【讨论】:

  • 这首歌有标签吗?
  • 您是指属性选项卡中的详细信息吗?是的。但它没有任何非法字符(:\/?"等)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多