Learner
Learner

Reputation: 672

Read file name then call a function with python

I want to read file name(A/B/C/D) and call the convenable function for each file in Files folder and then process the next file (pass automatically to the next file and function).

I have multiple files stored in File_folder folder:

Here is the directory structure:

       App/  
       ├─ main.py
       └─ Files/  
       |   └─B.txt
       |   └─A.xlsx
       |   └─D.xlsx    
       |   └─C.csv
       └─ File_output/

I have multiple functions stored in main.py:

def A_fct(fileA):
    pass
def B_fct(fileB):
    pass
def C_fct(fileC):
    pass
def D_fct(fileD):
    pass
def E_fct(fileE):
    pass
def F_fct(fileF):
    pass

Example:

read file Name B.txt => call B_fct

read file Name A.xlsx => call A_fct

etc ...

How can i do this please!

I have read all the suggestions belows but still don't know how to do it.

Upvotes: 0

Views: 773

Answers (1)

Almog-at-Nailo
Almog-at-Nailo

Reputation: 1182

If I understand the question correctly, you want to call a certain function for each file depending on the name of the file

you can define a dict with the relationship file_name => function

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

then call the function with

name_to_func[file_name](file_name)

Edit:

Now I understand that you want to iterate over files in a folder, you can do that with os.listdir(path).

for example, something like this:

import os

path = '/your/path/here'

name_to_func = {
    "A": A_fct,
    "B": B_fct
}

for file_name in os.listdir(path):
    file_prefix = file_name.split('.')[0]
    name_to_func[file_prefix](file_name)

Upvotes: 2

Related Questions