维护一对文件的数据结构

Data structure to maintain a pair of files

背景

有两个文件,名称为 alertfileeventfile

这个文件对位于多个文件夹中(如下所示),每个文件对具有不同的内容。

识别文件对名称与其他对不同的唯一方法是通过文件夹结构,它们位于。

文件将始终以只读模式打开,使用 python 文件 api in Linux。

关于内容,一对文件与另一对文件没有关系。

没有关于文件夹结构深度的线索。

文件夹名称未知(提前)。

并不是每个文件夹都有这些文件对。某些文件夹可能只有包含这些文件对的子文件夹。所以,文件夹可以是空的。

每个文件对的大小为 KB,并且是静态文件。

root_folder
 |
 |
 +---folder1
 |       | 
 |       |___ alertfile
 |       |___ eventfile
 |
 +---folder2
 |       |
 |       |___ alertfile
 |       |___ eventfile
 |       |
 |       +--- folder_2_1
 |            |
 |            |___alertfile
 |            |___eventfile
 |            |
 |            +---folder_2_1_1
 |                |
 |                |___alertfile
 |                |___eventfile
 |          
 |      
 +---folder3
 |       |
 |       |___ alertfile
 |       |___ eventfile
 |
 +---folder4
 |       |
 |       +---folder4_1
 |             |
 |             |____ alertfile
 |             |____ eventfile
 |             |
 |             +---folder4_1_1(empty) 
 :
 :
 :

目标

出于不同的目的,需要在不同的代码区域访问所有这些文件对的内容。


程序是一个服务器程序...维护这些文件对的缓存...

1) 我应该使用哪种数据结构来有效地访问这些文件对?实际解析这些文件对中的内容....出于多种原因

2) 将每个文件对的内容放在一对数据结构中会更快吗?并输入文件夹路径..

3) 在创建缓存之前可以多线程读取文件吗?因为 python GIL 允许 IO 绑定线程交错..

我建议使用嵌套字典来缓存 alertfileeventfile 对。由于一个文件夹可能包含也可能不包含文件对,当它包含时,它应该使用 '.' 键来存储该文件夹中文件对的字典,如下所示:

cache = {
    '.': {'alertfile': 'alert content', 'eventfile': 'event content'},
    'hello': {
        'foo': {'.': {'alertfile': 'alert content', 'eventfile': 'event content'}},
        'bar': {'.': {'alertfile': 'alert content', 'eventfile': 'event content'}}
    },
    'world': {
        'aloha': {
            '.': {'alertfile': 'alert content', 'eventfile': 'event content'},
            'hi': {'.': {'alertfile': 'alert content', 'eventfile': 'event content'}},
            'hey': {'.': {'alertfile': 'alert content', 'eventfile': 'event content'}}
        }
    },
    'empty': {}
}

这是一个递归函数,它扫描给定目录,读取其中的任何文件对,returns上述数据结构中的字典。

from os import listdir
from os.path import isdir, join

def scan_files(dir):
    cache = {}
    for name in listdir(dir):
        path = join(dir, name)
        if isdir(path):
            cache[name] = scan_files(path)
        elif name in ('alertfile', 'eventfile'):
            with open(path, 'r') as file:
                cache['.'][name] = file.read()
    return cache

如果你想加速这个过程,你可以把上面 for 循环中的块放到线程池中。

或者,如果您更喜欢将文件缓存在平面字典中,则可以使用 os.walk 来循环遍历整个目录。

import os
def scan_files(dir):
    cache = {}
    for root, dirs, files in os.walk(dir):
        for name in files:
            if name in ('alertfile', 'eventfile'):
                path = os.path.join(root, name)
                with open(path, 'r') as file:
                    cache[path] = file.read()
    return cache