用unicode文件名打开文件?

12 python unicode file

我似乎无法打开具有unicode文件名的文件.让我们说:

for i in os.listdir():
    open(i, 'r')
Run Code Online (Sandbox Code Playgroud)

当我尝试搜索某些解决方案时,我总是得到关于如何读取和写入unicode字符串到文件的页面,而不是如何打开带有unicode名称的文件file()或者open()具有unicode名称的文件.

Gar*_*tty 28

只需传递open()一个unicode字符串作为文件名:

在Python 2.x中:

>>> open(u'someUnicodeFilename?')
<open file u'someUnicodeFilename\u03bb', mode 'r' at 0x7f1b97e70780>
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中,所有字符串都是Unicode,因此几乎没有任何字符串.

与往常一样,注意,要打开一个文件的最好方法是始终使用with的语句与结合open().

编辑:关于os.listdir()建议再次变化,在Python 2.x下,你必须要小心:

os.listdir(),它返回文件名,引发了一个问题:它应该返回Unicode版本的文件名,还是应该返回包含编码版本的8位字符串?os.listdir()将执行这两个操作,具体取决于您是将目录路径提供为8位字符串还是Unicode字符串.如果传递Unicode字符串作为路径,则将使用文件系统的编码对文件名进行解码,并返回Unicode字符串列表,而传递8位路径将返回文件名的8位版本.

资源

简而言之,如果你想要Unicode输出,请将Unicode放入:

>>> os.listdir(".")
['someUnicodeFilename\xce\xbb', 'old', 'Dropbox', 'gdrb']
>>> os.listdir(u".")
[u'someUnicodeFilename\u03bb', u'old', u'Dropbox', u'gdrb']
Run Code Online (Sandbox Code Playgroud)

请注意,该文件仍将以任何方式打开 - 它不会在Python中很好地表示,因为它将是一个8位字符串,但它仍然可以工作.

open('someUnicodeFilename\xce\xbb')
<open file 'someUnicodeFilename?', mode 'r' at 0x7f1b97e70660>
Run Code Online (Sandbox Code Playgroud)

在3.x下,一如既往,它始终是Unicode.

  • 请注意,filesystemencoding在Windows下永远不是UTF,因此任何不在您的语言环境代码页中的字符都将导致非Unicode版本失败. (3认同)

Tha*_*sas 8

你可以试试这个:

import os
import sys

for filename in os.listdir(u"/your-direcory-path/"):
  open(filename.encode(sys.getfilesystemencoding()), "r")
Run Code Online (Sandbox Code Playgroud)