5

I am running my python code on Windows and trying to traverse and store all the file name with their paths in a file. But the Windows has a restriction of 260 characters.

os.chdir(self.config.Root_Directory_Path())        
    for root, dirs, files in os.walk("."):
        file_list.extend( join(root,f) for f in files )
    file_name_sorted = sorted(file_list)
    #file_sorted = sorted(file_list, key=getsize)
    #time.strftime("%m/%d/%Y %I:%M:%S %p" ,time.localtime(os.path.getmtime(file)))
    f = open(self.config.Client_Local_Status(),'wb')        
    for file_name in file_name_sorted:
        if (os.path.exists(file_name)):
            #f.write((str(os.path.getmtime(file_name)) + "|" + file_name + "\n").encode('utf-8'))
            pass
        else:
            print(file_name + "|" + str(len(file_name) + len(originalPath)) + "\n")
            print(os.path.getmtime(file_name))
            #f.write((str(os.path.getmtime(file_name)) + "|" + file_name + "\n").encode('utf-8'))
    f.close()

Because of the error, os.path.getmtime(file_name) throws an exception file not found. How can I overcome this problem? I tried using //?/ character as prefix, as suggested in

http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx

But was not successful in using //?/ character.

I tried using os.path.getmtime("////?//" + file_name) #Threw an error invalid path

Please suggest a fix

4

1 回答 1

9

这里的问题是您使用的是相对路径。\\?\前缀只能应用于绝对路径。正如文档所说:

这些前缀不用作路径本身的一部分。它们表明路径应该以最少的修改传递给系统,这意味着您不能使用正斜杠来表示路径分隔符,或者使用句点来表示当前目录,或者使用双点来表示父目录。因为您不能将“ \\?\”前缀与相对路径一起使用,所以相对路径总是被限制为总共MAX_PATH个字符。

修复很简单。而不是这个:

'\\\\?\\' + file_name

做这个:

'\\\\?\\' + os.path.abspath(file_name)

您不能使用正斜杠。添加额外的反斜杠可能合法也可能不合法,在这种情况下,您可以r'\\?\\'不用加倍双反斜杠而不是加倍。试试看(但请确保测试驱动器前缀路径C:\foo和 UNC 路径\\server\share\bar)......但是上面的双反斜杠版本肯定可以工作。

于 2012-11-17T01:45:19.357 回答