【发布时间】:2016-02-11 19:03:37
【问题描述】:
这是我第一次在这里写作,所以我希望我一切都好。 我在 Win10 上使用 python 3.5,我正在尝试将音乐从 Itunes“同步”到我的 Android 设备。基本上,我正在阅读 Itunes Library XML 文件并获取所有文件的位置(这样我就可以将它们复制/粘贴到我的手机中),但是我遇到了包含外来字符的歌曲的问题。
import getpass
import re
import os
from urllib.parse import unquote
user = getpass.getuser()
ITUNES_LIB_PATH = "C:\\Users\\%s\\Music\\Itunes\\iTunes Music Library.xml" % user
ITUNES_SONGS_FILE = "ya.txt"
def write(file, what, newline=True):
with open(file, 'a', encoding="utf8") as f:
if not os.path.isfile(what):
print("Issue locating file %s\n" % what)
if newline:
what+"\n"
f.write(what)
def get_songs(file=ITUNES_LIB_PATH):
with open(file, 'r', encoding="utf8") as f:
f = f.read()
songs_location = re.findall("<key>Location</key><string>file://localhost/(.*?)</string>", f)
for song in songs_location:
song = unquote(song.replace("/", '\\'))
write(ITUNES_SONGS_FILE, song)
get_songs()
输出:
Issue locating file C:\Users\Dymy\Desktop\Media\Norin &amp; Rad - Bird Is The Word.mp3
我应该如何处理那个“&”在文件名中?
【问题讨论】:
-
也许你可以再次使用
replace()将所有&amp;s 变成& -
或使用 html 库,如答案on here
-
感谢@RNar,它解决了这个问题!我想知道是否有办法避免 utf8 编码避免 read() 和 write()...
-
&#38;amp;是转义两次的 & 符号。这与任何字符编码无关。 -
我必须通过将“utf8”设置为编码来克服 UnicodeError,这会改变字符串并导致文件路径错误,我想知道是否有任何方法可以在不编码为 utf8 的情况下使用这些路径。 @roeland
标签: python xml unicode itunes python-3.5