我有一个 PHP 脚本,可以在目录中创建文件列表,但是,PHP 只能看到英文的文件名,而完全忽略其他语言的文件名,例如俄语或亚洲语言。
经过大量努力,我找到了唯一适合我的解决方案 - 使用 python 脚本将文件重命名为 UTF8,因此 PHP 脚本可以在此之后处理它们。
(PHP 处理完文件后,我将文件重命名为英文,我不将它们保存为 UTF8)。
我使用了以下 python 脚本,效果很好:
import sys
import os
import glob
import ntpath
from random import randint
for infile in glob.glob( os.path.join('C:\\MyFiles', u'*') ):
if os.path.isfile(infile):
infile_utf8 = infile.encode('utf8')
os.rename(infile, infile_utf8)
问题是它还转换了已经在 UTF8 中的文件名。如果文件名已经是 UTF8,我需要一种跳过转换的方法。
我正在尝试这个python脚本:
for infile in glob.glob( os.path.join('C:\\MyFiles', u'*') ):
if os.path.isfile(infile):
try:
infile.decode('UTF-8', 'strict')
except UnicodeDecodeError:
infile_utf8 = infile.encode('utf8')
os.rename(infile, infile_utf8)
但是,如果文件名已经在 utf8 中,我会收到致命错误:
UnicodeDecodeError: 'ascii' codec can't decode characters in position 18-20
ordinal not in range(128)
我还尝试了另一种方法,但也没有用:
for infile in glob.glob( os.path.join('C:\\MyFiles', u'*') ):
if os.path.isfile(infile):
try:
tmpstr = str(infile)
except UnicodeDecodeError:
infile_utf8 = infile.encode('utf8')
os.rename(infile, infile_utf8)
我得到了与以前完全相同的错误。
有任何想法吗?
Python 对我来说很新,即使是一个简单的脚本调试对我来说也是一个巨大的努力,所以请写一个明确的答案(即代码)。我没有能力测试可能有效或无效的一般想法。谢谢。
文件名示例:
hello.txt
你好.txt
안녕하세요.html
chào.doc