gpt4 book ai didi

python - 如何获得路径的正确大写?

转载 作者:可可西里 更新时间:2023-11-01 11:28:31 25 4
gpt4 key购买 nike

假设我有一个代表目录的类(当然是简化示例):

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

为了让事情更容易在内部实现,我调用os.path.normcase在将其保存到属性之前在 path 参数上。这很好用,但它会将路径小写:

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

我想要一种方法将路径变回其正确大写的形式 C:\Python34\Lib。我计划在 __repr__ 方法中执行此操作,以便我可以获得不错的输出,例如:

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

当我在交互式解释器中时。标准库中有这样的东西吗?


注意:我指的不是用户作为 path 参数提供的字符串。如果用户这样做:

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

我仍然希望在解释器中打印 Dir('C:\Python34\Lib'),因为这是正确的大写。基本上,我希望输出的路径与文件资源管理器中的路径相同。

最佳答案

更新:

对于使用较新版本 Python 的用户,新的 pathlib modulepathlib.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'
>>>

因此,您可以将用户提供的路径存储为 Path 对象:

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

然后像这样实现__repr__方法:

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

作为额外的好处,我们不再需要 os.path.normcase 函数,因为 Path 对象直接支持不区分大小写的比较。

pathlib 的一个缺点是它仅在 Python 3.4(当前最新版本)中可用。因此,那些使用早期版本的用户将需要向后移植到他们的版本或使用 os.path._getfinalpathname 函数,如下所示。


当我深入研究标准库时,我在名为 _getfinalpathnameos.path 模块中遇到了一个未记录的函数:

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

使用 str.lstrip ,我可以获得我需要的输出:

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

此方法的唯一缺点是该函数未记录且有些隐藏。但它现在适合我的需要(当然,如果你知道一个更好的方法,我很想听听:)

关于python - 如何获得路径的正确大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com