英文:
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'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 = ['daily', 'bills', 'costs', 'names', 'ids']
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 = ['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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论