tyl*_*eax 3 python object python-3.x
我正在尝试找到一种将文件结构表示为 python 对象的方法,这样我就可以轻松获得特定路径,而不必键入所有字符串。这适用于我的情况,因为我有一个静态文件结构(不变)。
我想我可以将目录表示为类,将目录中的文件表示为类/静态变量。
我希望能够浏览 python 对象,以便它返回我想要的路径,即:
print(FileStructure.details.file1) # root\details\file1.txt
print(FileStructure.details) # root\details
Run Code Online (Sandbox Code Playgroud)
我从下面的代码中得到的是:
print("{0}".format(FileStructure())) # root
print("{0}".format(FileStructure)) # <class '__main__.FileStructure'>
print("{0}".format(FileStructure.details)) # <class '__main__.FileStructure.details'>
print("{0}".format(FileStructure.details.file1)) # details\file1.txt
Run Code Online (Sandbox Code Playgroud)
到目前为止我拥有的代码是......
import os
class FileStructure(object): # Root directory
root = "root"
class details(object): # details directory
root = "details"
file1 = os.path.join(root, "file1.txt") # File in details directory
file2 = os.path.join(root, "file2.txt") # File in details directory
def __str__(self):
return f"{self.root}"
def __str__(self):
return f"{self.root}"
Run Code Online (Sandbox Code Playgroud)
我不想必须实例化该类才能完成这项工作。我的问题是:
首先:您可能实际上并不想要这个。Python3 的pathlibAPI 看起来比这更好,并且已经得到了广泛的支持。
root = pathlib.Path('root')
file1 = root / 'details' / 'file1' # a Path object at that address
if file1.is_file():
file1.unlink()
else:
try:
file1.rmdir()
except OSError as e:
# directory isn't empty
Run Code Online (Sandbox Code Playgroud)
但是,如果您出于某种原因对此一意孤行,则需要重写__getattr__以创建新FileStructure对象并跟踪父母和孩子。
class FileStructure(object):
def __init__(self, name, parent):
self.__name = name
self.__children = []
self.__parent = parent
@property
def parent(self):
return self.__parent
@property
def children(self):
return self.__children
@property
def name(self):
return self.__name
def __getattr__(self, attr):
# retrieve the existing child if it exists
fs = next((fs for fs in self.__children if fs.name == attr), None)
if fs is not None:
return fs
# otherwise create a new one, append it to children, and return it.
new_name = attr
new_parent = self
fs = self.__class__(new_name, new_parent)
self.__children.append(fs)
return fs
Run Code Online (Sandbox Code Playgroud)
然后将其与以下命令一起使用:
root = FileStructure("root", None)
file1 = root.details.file1
Run Code Online (Sandbox Code Playgroud)
您可以添加__str__和__repr__来帮助您的表述。您甚至可以包括一个path属性
# inside FileStructure
@property
def path(self):
names = [self.name]
cur = self
while cur.parent is not None:
cur = cur.parent
names.append(cur.name)
return '/' + '/'.join(names[::-1])
def __str__(self):
return self.path
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1697 次 |
| 最近记录: |