获取名称包含特殊(非ASCII)字符的文件的属性



当文件名包含非ASCII字符时,我正在使用python,在读取文件属性时遇到一些问题。

例如,其中一个文件名为:

0-Channel-https∺∯∯services.apps.microsoft.com∯browse∯6.2.9200-1∯615∯Channel.dat

当我运行这个:

list2 = os.listdir('C:\Users\James\AppData\Local\Microsoft\Windows Store\Cache Medium IL\0\')
for data in list2:
    print os.path.getmtime(data) + 'n'

我得到错误:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: '0-Channel-https???services.apps.microsoft.com?browse?6.2.9200-1?615?Channel.dat'

我认为这是由特殊字符引起的,因为代码与其他只有ASCII字符的文件名配合使用很好。

有人知道这样命名的文件的文件系统属性的查询方法吗?

如果这是python 2.x,那就是编码问题。如果将unicode字符串传递给os.listdir(如u'C:\my\pathname'),它将返回unicode字符串,并且它们应该具有正确编码的非ascii字符。请参阅文档中的Unicode文件名。

引用文档:

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

这个代码应该可以工作。。。

directory_name = u'C:\Users\James\AppData\Local\Microsoft\Windows Store\Cache Medium IL\0\'
list2 = os.listdir(directory_name)
for data in list2:
    print data, os.path.getmtime(os.path.join(directory_name, data))

当你在windows中时,你应该尝试使用ntpath模块,而不是os.path

from ntpath import getmtime

由于我没有windows,我无法测试它。每个操作系统都有不同的路径约定,因此,Python为最常见的操作系统提供了一个特定的模块。

最新更新