【发布时间】:2015-02-06 12:32:35
【问题描述】:
我正在尝试编写一个 Python 脚本,该脚本通过目录树搜索并列出所有 .flac 文件并从相应的导出 Arist、Album 和 Title。 dir/subdir/filename 并将其写入文件。该代码工作正常,直到它遇到一个 unicode 字符。代码如下:
import os, glob, re
def scandirs(path):
for currentFile in glob.glob(os.path.join(path, '*')):
if os.path.isdir(currentFile):
scandirs(currentFile)
if os.path.splitext(currentFile)[1] == ".flac":
rpath = os.path.relpath(currentFile)
print "**DEBUG** rpath =", rpath
title = os.path.basename(currentFile)
title = re.findall(u'\d\d\s(.*).flac', title, re.U)
title = title[0].decode("utf8")
print "**DEBUG** title =", title
fpath = os.path.split(os.path.dirname(currentFile))
artist = fpath[0][2:]
print "**DEBUG** artist =", artist
album = fpath[1]
print "**DEBUG** album =", album
out = "%s | %s | %s | %s\n" % (rpath, artist, album, title)
flist = open('filelist.tmp', 'a')
flist.write(out)
flist.close()
scandirs('./')
代码输出:
**DEBUG** rpath = Thriftworks/Fader/Thriftworks - Fader - 01 180°.flac
**DEBUG** title = 180°
**DEBUG** artist = Thriftworks
**DEBUG** album = Fader
Traceback (most recent call last):
File "decflac.py", line 25, in <module>
scandirs('./')
File "decflac.py", line 7, in scandirs
scandirs(currentFile)
File "decflac.py", line 7, in scandirs
scandirs(currentFile)
File "decflac.py", line 20, in scandirs
out = "%s | %s | %s | %s\n" % (rpath, artist, album, title)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 46: ordinal not in range(128)
但是当在 Python 控制台中尝试时,它工作正常:
>>> import re
>>> title = "Thriftworks - Fader - 01 180°.flac"
>>> title2 = "dummy"
>>> title = re.findall(u'\d\d\s(.*).flac', title, re.U)
>>> title = title[0].decode("utf8")
>>> out = "%s | %s\n" % (title2, title)
>>> print out
dummy | 180°
所以,我的问题: 1)为什么相同的代码在控制台中有效,但在脚本中无效? 2) 如何修复脚本?
【问题讨论】:
标签: python regex unicode findall