Skip to main content
 首页 » 编程设计

python之os.listdir 返回带有神秘字符的列表

2025年05月04日19shangdawei

我在目录上执行 os.listdir(),它返回如下列表:

[u'Somefile.gif', u'SomeDirectory', u'SomeJPEG.jpeg'] 

你的目的是什么?在我的搜索中,我听说这个:

  1. 是一个固定的错误。
  2. 表示列出的项目是 unicode。

我不相信这些都是真的。

请您参考如下方法:

在Python2中,u'...'中的u表示对象是unicode。

From the docs :

Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. Undecodable filenames will still be returned as string objects.

也许您正在使用 unicode 参数调用 os.listdir。例如:

In [51]: import os 
 
In [52]: os.listdir('.') 
Out[52]: ['a', 'a.ps'] 
 
In [53]: os.listdir(u'.') 
Out[53]: [u'a', u'a.ps']