0

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

文件名格式为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 首歌曲中唯一的一首,但我想知道我未来的理解。

作为旁注,这是我第一个有用的代码!最欢迎优化批评。

4

1 回答 1

0

你能试着替换这些行吗

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()))

谢谢

于 2019-04-13T23:29:26.510 回答