Long paths in Python on Windows

前端 未结 3 428
星月不相逢
星月不相逢 2020-11-30 07:40

I have a problem when programming in Python running under Windows. I need to work with file paths, that are longer than 256 or whatsathelimit characters. Now, I\'ve read ba

相关标签:
3条回答
  • 2020-11-30 08:16

    Well it seems that, as always, I've found the answer to what's been bugging me for a week twenty minutes after I seriously ask somebody about it.

    So I've found that I need to make sure two things are done correctly:

    1. The path can contain only backslashes, no forward slashes.
    2. If I want to do something like list a directory, I need to end the path with a backslash, otherwise Python will append /*.* to it, which is a forward slash, which is bad.

    Hope at least someone will find this useful.

    0 讨论(0)
  • 2020-11-30 08:22

    py 3.8.2

    # Fix long path access:
    import ntpath
    ntpath.realpath = ntpath.abspath
    # Fix long path access.
    

    In my case, this solved the problem of running a script from a long path. (https://developers.google.com/drive/api/v3/quickstart/python) But this is not a universal fix. It looks like the ntpath.realpath implementation has problems. This code replaced it with a dummy.

    0 讨论(0)
  • 2020-11-30 08:28

    Let me just simplify this for anyone looking for a straight answer:

    1. Path needs to be unicode, prepend string with u like u'C:\\path\\to\\file'
    2. Path needs to start with \\\\?\\ (which is escaped into \\?\) like u'\\\\?\\C:\\path\\to\\file'
    3. No forward slashes only backslashes: / --> \\
    4. It has to be an absolute path; it does not work for relative paths
    0 讨论(0)
提交回复
热议问题