维护一对文件的数据结构

2024-09-23 22:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

背景

有两个文件名为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绑定的线程交错。。你知道吗


Tags: 文件方法文件夹名称数据结构内容文件名模式
1条回答
网友
1楼 · 发布于 2024-09-23 22:25:52

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

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': {}
}

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

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循环中的块放入线程池。你知道吗

或者,如果您喜欢将文件缓存在平面dict中,那么可以使用^{}来遍历循环中的整个目录。你知道吗

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

相关问题 更多 >