【问题标题】:find a file with specific extension anywhere in the system在系统中的任何位置查找具有特定扩展名的文件
【发布时间】:2022-01-02 09:14:00
【问题描述】:

我需要为我在 Python 3.9 中定义的函数编写测试代码。由于该函数应该接收特定扩展名及其路径的文件,然后在 Python 中加载它,因此我的测试应该查找该扩展名的任何可用文件并尝试正确加载它。 我该如何编码?

【问题讨论】:

  • 最简单的方法是使用 pathlib 中的 glob(或 rglob)docs

标签: python function file testing path


【解决方案1】:

也许这会有所帮助:

import os
file_path = '/' # Location of files
file_extension = 'xlsx'
for i in os.listdir(file_path):
    if file_extension == i.split('.')[-1]:
        print(i)  # The task you want to perform with the specific files

这里file_path是文件列表的路径,file_extension是我们要搜索的具体扩展名。

【讨论】:

    猜你喜欢
    • 2011-03-13
    • 2011-03-10
    • 2011-08-21
    • 2019-07-21
    • 2012-01-26
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多