小编Phy*_*ser的帖子

Python 如何检查文件名是否为 UTF8?

我有一个 PHP 脚本,可以在目录中创建文件列表,但是,PHP 只能看到英文文件名,而完全忽略其他语言(例如俄语或亚洲语言)的文件名。

\n\n

经过大量努力,我找到了唯一适合我的解决方案 - 使用 python 脚本将文件重命名为 UTF8,以便 PHP 脚本可以在之后处理它们。

\n\n

(PHP处理完文件后,我将文件重命名为英文,不将它们保留为UTF8)。

\n\n

我使用了以下 python 脚本,效果很好:

\n\n
import sys\nimport os\nimport glob\nimport ntpath\nfrom random import randint\n\nfor infile in glob.glob( os.path.join('C:\\\\MyFiles', u'*') ):\n    if os.path.isfile(infile):\n      infile_utf8 = infile.encode('utf8')\n      os.rename(infile, infile_utf8)\n
Run Code Online (Sandbox Code Playgroud)\n\n

问题是它还会转换已经采用 UTF8 格式的文件名。我需要一种方法来跳过转换,以防文件名已经是 UTF8。

\n\n

我正在尝试这个 python 脚本:

\n\n
for infile in glob.glob( os.path.join('C:\\\\MyFiles', u'*') ):\n    if os.path.isfile(infile):\n      try:\n        infile.decode('UTF-8', 'strict')\n      except UnicodeDecodeError:\n        infile_utf8 = infile.encode('utf8')\n        os.rename(infile, infile_utf8)    \n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,如果文件名已经是 utf8 格式,我会收到致命错误:

\n\n
UnicodeDecodeError: 'ascii' codec can't …
Run Code Online (Sandbox Code Playgroud)

python windows unicode filenames utf-8

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

filenames ×1

python ×1

unicode ×1

utf-8 ×1

windows ×1