读取文件名,然后使用 python 调用方便的函数(带有一个或两个参数)

Read file name then call the convenable function (with one or two arguments) using python

我想读取文件名(A/B/C/D)并为文件夹中的每个文件调用可调用函数,然后处理下一个文件(自动传递到下一个文件和函数)。

我在文件夹中存储了多个文件:

目录结构如下:

   App/  
   ├─ main.py
   └─ Files/  
      └─B.txt
      └─A.xlsx
      └─folderC
      |   └─filec1.txt
      |   └─filec2.txt
      └─D.xlsx    
      └─folderF
         └─fileF1.txt
         └─fileF2.txt

我在 main.py 中存储了多个函数:

def A_fct(fileA):
    pass
def B_fct(fileB):
    pass
def C_fct(fileC1,fileC2):
    pass
def D_fct(fileD):
    pass
def F_fct(files):
    df = pd.concat([pd.read_csv(f,sep='\t',engine="python") for f in 
        glob.glob(files + "/*.txt")],ignore_index=True)

注意:有些函数有 2 个参数。

示例:

读取文件名B.txt =>调用B_fct

读取文件名A.xlsx =>调用A_fct

等...

我试过这个解决方案:

path = ''

name_to_func = {
        "A.xlsx": A_fct,
        "B.txt": B_fct,
        ...
}

for files in os.listdir(path):
    name_to_func[file_name](files)

当函数 只有一个参数 时,这个解决方案对我来说非常有效,但有时我有例外,我有一个函数 Exp C_fct(fileC1,fileC2)

的 2 个参数

请问我该如何解决这个问题!

您可以检查路径是否为带 os.path.isdir 的目录并更改调用参数。

base_path = 'Files/'
for name in os.listdir(base_path):
    path = os.path.join(base_path, name)
    if os.path.isdir(path):
        files = [os.path.join(path, f) for f in os.listdir(path)]
        if name_to_func[path].__code__.co_argcount == len(files):
            name_to_func[path](*files)
        else:
            name_to_func[path](files)
    else:
        name_to_func[path](path)

在这种情况下,文件列表将用作函数的参数。

如果您不确定该函数将获得多少个参数,您也可以重写定义:

def C_fct(*files):
    files  # is the list of arguments

但是,您可以避免 * 简单地提供列表作为参数的表示法。