【发布时间】:2016-01-17 09:12:00
【问题描述】:
在我的小项目中,我必须识别目录中的文件类型。所以我选择了python-magic 模块并做了以下事情:
from Tkinter import Tk
from tkFileDialog import askdirectory
def getDirInput():
root = Tk()
root.withdraw()
return askdirectory()
di = getDirInput()
print('Selected Directory: ' + di)
for f in os.listdir(di):
m = magic.Magic(magic_file='magic')
print 'Type of ' + f + ' --> ' + m.from_file(f)
但是当我将它传递给from_file() 函数时,python-magic 似乎无法采用 unicode 文件名。这是一个示例输出:
Selected Directory: C:/Users/pruthvi/Desktop/vidrec/temp
Type of log.txt --> ASCII English text, with very long lines, with CRLF, CR line terminators
Type of TAEYEON 태연_ I (feat. Verbal Jint)_Music Video.mp4 --> cannot open `TAEYEON \355\234\227_ I (feat. Verbal Jint)_Music Video.mp4' (No such file or directory)
Type of test.py --> a python script text executable
您可以观察到 python-magic 无法识别第二个文件 TAEYEON... 的类型,因为其中包含 unicode 字符。它将태연 字符显示为\355\234\227,而我在两种情况下都通过了相同的字符。我怎样才能克服这个问题并找到带有 Unicode 字符的文件类型呢?谢谢你
【问题讨论】:
-
Python 2.x 还是 Python 3?
-
如果对文件名进行编码会发生什么?
m.from_file(f.encode(sys.getfilesystemencoding())) -
@AlastairMcCormack,Python 2.x
-
@falsetru ,IO 错误指出文件不存在,因为 unicode 字符被替换为 '??'显然是错误的
-
这个怎么样?
m.from_file(os.path.join(di, f))