在python中,从类外部访问类内的多个列表(或其他变量)

2024-06-16 09:36:11 发布

您现在位置: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']

谢谢你的帮助


Tags: 文件inself内容列表foroutputdef
1条回答
网友
1楼 · 发布于 2024-06-16 09:36:11

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

文件1.txt

contents
of 
file 
one

文件2.txt

contents
of 
file 
two

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

然后可以从每个文件的^{}列表中收集行。然后,您可以调用此词典中的文件,并对行内容列表进行处理

演示:

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']

相关问题 更多 >