首页 > 解决方案 > 从python中的类外部访问一个类中的多个列表(或其他变量)

问题描述

以前有人问过这个问题,但是我找不到,对不起,我想知道是否有一种方法可以在一个类中访问(或保存)多个列表(或其他变量)的内容,而无需创建列表列表,然后在类之外解构列表列表。

这是一个例子

它是一个在选定文件类型的目录中打开所有文件并将每个文件的内容输出为列表的类

class WithOpenFilesInDirectory:
def __init__(self, Directory, FileType):
    self.Directory = Directory
    self.FileType = FileType
def LoadFilesList(self):
    for filename in glob.glob(os.path.join(self.Directory, self.FileType)):
        with open(filename, "r") as Output:
            print(filename)
            Output = Output.readlines()
            Output = [x.strip("\n") for x in Output]
            print(Output)

WithOpenFilesInDirectory("data","*txt").LoadFilesList()

这是我正在寻找的结束格式的示例,在课堂之外

File1 = ['contents', 'of', 'file', 'one']
File2 = ['contents', 'of', 'file', 'two']

谢谢你的帮助

标签: pythonpython-3.x

解决方案


为简单起见,假设我们的两个文件如下所示:

文件1.txt

contents
of 
file 
one

文件2.txt

contents
of 
file 
two

它们存储在data我们的脚本所在的目录中。

然后,您可以从列表中的每个文件中收集行collections.defaultdict。然后,您可以从该字典中调用文件并对行内容列表执行某些操作。

演示:

from glob import glob

from os.path import join
from os.path import basename
from os.path import splitext

from collections import defaultdict

class OpenFilesDirectory:
    def __init__(self, directory, filetype):
        self.path = join(directory, filetype)

    def load_files_list(self):
        lines = defaultdict(list)

        for filename in glob(self.path):
            name, _ = splitext(basename(filename))
            with open(filename) as f:
                for line in f:
                    lines[name].append(line.strip())

        return lines

d = OpenFilesDirectory("data", "*.txt").load_files_list()
print(d)

输出:

defaultdict(<class 'list'>, {'File1': ['contents', 'of', 'file', 'one'], 'File2': ['contents', 'of', 'file', 'two']})

然后,您可以像这样访问这些行:

>>> d['File1']
['contents', 'of', 'file', 'one']
>>> d['File2']
['contents', 'of', 'file', 'two']

推荐阅读