当文件名包含非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字符的其他文件名。
有没有人知道一种查询名为this?
的文件的文件系统属性的方法答案 0 :(得分:1)
如果这是python 2.x,那就是编码问题。如果将unicode字符串传递给os.listdir(例如u'C:\\my\\pathname'
),它将返回unicode字符串,并且它们应该正确编码非ascii字符。请参阅文档中的Unicode Filenames。
引用文档:
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))
答案 1 :(得分:0)
当你在Windows中时,你应该尝试使用ntpath模块而不是os.path
from ntpath import getmtime
由于我没有窗户,我无法测试它。每个操作系统都有不同的路径约定,因此,Python为最常见的操作系统提供了一个特定的模块。