首页 > 解决方案 > 维护一对文件的数据结构

问题描述

背景

有两个名为alertfile&的文件eventfile

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

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

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

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

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

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

每个文件夹可能没有这些文件对。某些文件夹可能只有具有这些文件对的子文件夹。所以,一个文件夹可以是空的。

每个文件对的大小是 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绑定线程交错..

标签: pythonmultithreadingalgorithmdata-structuresfilesystems

解决方案


我建议使用嵌套字典来缓存你的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': {}
}

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

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

推荐阅读