python - 从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']
谢谢你的帮助
解决方案
为简单起见,假设我们的两个文件如下所示:
文件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']
推荐阅读
- javascript - 如何在 javascript 文件中使用 resx 文件。.net 核心 3.1 mvc
- c# - 如何撤消 SetWindowDisplayAffinity 方法?
- javascript - 如何在 JavaScript 中在浏览器中创建选择?
- angular - 嗨,我用 swiper angular 遇到了这个错误
- vb.net - 每次按下键都会在文本框 VB.NET 中自动显示小数位
- javascript - HTML - 带有 ahref 和按钮的下拉菜单
- java - 在 Spring Boot 2.4 中从配置服务器读取属性
- mysql - 如何在 MySQL 中使用复合主键在同一张表上创建 nn 关系
- python - Pyqt5 中的 matplotlib.plot
- java - 尝试通过rabbitMQ实现nexmo SDK的调用入站时发生java.lang.AbstractMethodError