How can I get the proper capitalization for a path?

巧了我就是萌 提交于 2019-12-13 02:04:36

问题


Let's say I have a class which represents a directory (simplified example of course):

import os
class Dir:
    def __init__(self, path):
        self.path = os.path.normcase(path)

To make things easier to implement internally, I am calling os.path.normcase on the path argument before I save it into an attribute. This works great, but it lowercases the path:

>>> import os
>>> os.path.normcase(r'C:\Python34\Lib')
'c:\\python34\\lib'
>>>

I would like a way to turn the path back into its properly capitalized form of C:\Python34\Lib. I plan to do this inside the __repr__ method so that I can get nice outputs such as:

>>> my_dir
Dir(r'C:\Python34\Lib')
>>>

when I am in the interactive interpreter. Is there anything like this in the standard library?


Note: I am not referring to the string that the user supplied as the path argument. If a user does:

my_dir = Dir('c:\PYTHON34\lib')

I still want Dir('C:\Python34\Lib') to be printed in the interpreter because that is the proper capitalization. Basically, I want the outputed paths to be the same as they are in the file explorer.


回答1:


Update:

For those using the newer versions of Python, the new pathlib module possesses this functionality in the form of pathlib.Path.resolve:

>>> from pathlib import Path
>>> Path(r'c:\python34\lib').resolve()
WindowsPath('C:/Python34/Lib')
>>> str(Path(r'c:\python34\lib').resolve())
'C:\\Python34\\Lib'
>>>

So, you could store the user-supplied path as a Path object:

from pathlib import Path
class Dir:
    def __init__(self, path):
        self.path = Path(path)

and then implement the __repr__ method like so:

def __repr__(self):
    return "Dir('{}')".format(self.path.resolve())

As an added bonus, we no longer need the os.path.normcase function since Path objects support case-insensitive comparisons directly.

One downside to pathlib though is that it is only available in Python 3.4 (the currently newest version). So, those using earlier versions will need to either get a backport to their version or use the os.path._getfinalpathname function as demonstrated below.


While I was digging through the standard library, I came across an undocumented function in the os.path module named _getfinalpathname:

>>> import os
>>> os.path._getfinalpathname(r'c:\python34\lib')
'\\\\?\\C:\\Python34\\Lib'
>>>

Using str.lstrip, I can get the output I need:

>>> os.path._getfinalpathname(r'c:\python34\lib').lstrip(r'\?')
'C:\\Python34\\Lib'
>>>

The only downside to this approach is that the function is undocumented and somewhat hidden. But it suits my needs for now (of course, I'd love to hear a better approach if you know of one :)



来源:https://stackoverflow.com/questions/27465610/how-can-i-get-the-proper-capitalization-for-a-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!