Home > Software design >  Find filename ending from arraylist
Find filename ending from arraylist

Time:08-12

Program: I'm trying to create a sorting program for multiple PDF files. Therefore I have a folder with PDFs listet for example like this: 001-x; 001-y1; 001-y2; 001-y3; 001-z; 002-x; 002-y1; 002-y2; ... I am running through all file names in the folder and also have array named "sort_by" (for the elements see code below). Problem: I now want to cycle through the array of files and move the current file to a folder if the file name includes any of the elements of sort_by. My Code so far:

sort_by = ["x", "z"]
my_path = #some path on PC

for root, directories, file in os.walk(my_path):
    for file in file:
        #this is the part that doesnt work
        if file.endswith(sort_by):
            #do something

I know that something like if file.endswith(x) or file.endswith(y): would work but I want the array to be adjustable in content and length. Any ideas?

CodePudding user response:

Use the any() function:

if any(file.endswith(ending) for ending in sort_by):
    # do something
  • Related