0

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.

10
  • Does this answer your question? python function call with variable Commented Aug 26, 2021 at 10:37
  • This has already been answered here where the function call is assigned to a variable Commented Aug 26, 2021 at 10:38
  • I already saw this answer and this is not what i need. I want to Automate the file reading and function applying Commented Aug 26, 2021 at 10:49
  • 1
    Which one is it? Those are two questions. SO questions should focus on one. Anyway, both of them are duplicates and already answered on this site. Please make sure to research before asking and only ask here as a last resort Commented Aug 26, 2021 at 11:25
  • 1
    First this: How do I list all files of a directory? then the link above Commented Aug 26, 2021 at 11:26

1 Answer 1

2
+50

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, exactly but i want to pass automatically to the next file and function
@Prestige What issues are you having with writing a loop over the folder's files?
@Prestige I edited the post. Hope these edits helped you with your problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.