检查列表中提到的所有文件是否存在于输入目录中。

huangapple go评论82阅读模式
英文:

Check if all files mentioned in a list are there in input directory

问题

我正在尝试创建一个验证函数
`def validate(path, name_list):`
该函数将接受一个字符串列表和一个路径。`name_list` 是一个包含预期文件名前缀的字符串列表文件名可能包含任何任意的后缀

```python
my_names_list = ['daily', 'bills', 'costs', 'names', 'ids']

目录中的文件名可能如下所示:

Daily_tue.xlsx
BILLS_26.05.2023.xlsx
Costs.xlsx

validate 函数应该报告在 path 目录中找不到文件名前缀的 my_name_list 中的哪些文件前缀。

例如,使用上述目录示例,输出应该是以下列表:

Missing files: names, ids

<details>
<summary>英文:</summary>

I&#39;m trying to create a validate function,
`def validate(path, name_list):` which will take a list of strings and a path. The `names_list` is a list of strings of expected file name prefixes. The file names may contain any arbitrary suffixes.


```python
my_names_list = [&#39;daily&#39;, &#39;bills&#39;, &#39;costs&#39;, &#39;names&#39;, &#39;ids&#39;]

The directory may have files names like this:

Daily_tue.xlsx
BILLS_26.05.2023.xlsx
Costs.xlsx

The validate function should report for which file prefixes in the my_name_list no file name is found in the path directory.

For instance, with the above directory example, the output should be the following list:

Missing files: names, ids

答案1

得分: 2

以下是翻译好的部分:

这是一个相当简单的、蛮力的解决方案,它检查给定的前缀是否至少与目录中要验证的任何文件名匹配:

import os

Name_list = ['daily', 'bills', 'costs', 'names', 'ids']

def validate(p, l):
    missing = set(l)
    f_names_in_path = os.listdir(p)

    for prefix in l:
        for f_name in f_names_in_path:
            if f_name.lower().startswith(prefix):
                missing.remove(prefix)
    return missing

print('Missing file prefixes: ', validate('path_to_your_files_to_test', Name_list))
英文:

Here is a rather simple, brute force solution that checks that a given prefix matches at least once any files name in the directory you are validating:

import os

Name_list = [&#39;daily&#39;, &#39;bills&#39;, &#39;costs&#39;, &#39;names&#39;, &#39;ids&#39;]


def validate(p, l):
    missing = set(l)
    f_names_in_path = os.listdir(p)

    for prefix in l:
        for f_name in f_names_in_path:
            if f_name.lower().startswith(prefix):
                missing.remove(prefix)
    return missing


print(&#39;Missing file prefixes: &#39;, validate(&#39;path_to_your_files_to_test&#39;, Name_list))

huangapple
  • 本文由 发表于 2023年5月29日 14:35:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76355139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定