0

My goal is to create a function that finds all the files of a specific type (extension) in a folder and places them in a list. As arguments of the function I set:

  1. file type (.xlsx, .png, .txt)
  2. the list name where the files will be placed

I was able to find all the files of a specific type. I was able to see the files in a list on my terminal I was NOT able to put the files in a list with the name of my choice so that later during the execution I can call the specific list with the name of my choice or any name. Could someone help me solve the problem? thanks in advance for understanding.

def find_all_filles_courrent_dir(type,namelist):
      # Η συνάρτηση βρίσκει όλα τα αρχεία τύπου type και τα τοποθετεί σε λίστα με όνομα namelist
    import glob
    x=str("*")+str(".")+str(type)
    namelist = [f for f in glob.glob(x)]
    
    print("Λίστα με τα αρχεία στον υπάρχον φάκελο είναι:",namelist)

    
find_all_filles_courrent_dir("xlsx","listafor")
print(listafor)

when I run :

> python3 try2.py
Λίστα με τα αρχεία στον υπάρχον φάκελο είναι: ['democreate.xlsx', 'test3.xlsx', 'test2.xlsx', 'test5.xlsx', 'test4.xlsx', 'test1.xlsx', 'teststable.xlsx']
Traceback (most recent call last):
  File "try2.py", line 11, in <module>
    print(listafor)
NameError: name 'listafor' is not defined


2
  • 2
    Please format your code correctly. But it seems like you have a fundamental misunderstanding how how functions work. Your function doesn't do anything with your list except print it, then returns nothing. You shouldn't try to dynamically create variables. Your function should return the list then do something like my_var = find_all_files_current_dir('xlsx') Note, you shouldn't use list as a variable name, because that is used for the built-in list type Commented Aug 16, 2020 at 15:03
  • please take a look again...i re-edit ... How can take all filles in one list? how can take the names as a object and put them in a list? thank you for your comment Commented Aug 16, 2020 at 15:57

1 Answer 1

1

Please use below code

def find_all_filles_courrent_dir(type,namelist):
      # Η συνάρτηση βρίσκει όλα τα αρχεία τύπου type και τα τοποθετεί σε λίστα με όνομα namelist
    import glob
    x=str("*")+str(".")+str(type)
    globals()[namelist] = [f for f in glob.glob(x)]
    
    print("Λίστα με τα αρχεία στον υπάρχον φάκελο είναι:",namelist)

    
find_all_filles_courrent_dir("xlsx","listafor")
print(listafor)
Sign up to request clarification or add additional context in comments.

Comments

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.