Search code examples
pythontuplescopying

Python endswith() function cannot avoid copying .py file


I am trying to copy some files based on extensions. My target is to copy everything except the extensions that are in my ext_to_avoid variable. However, I am failing miserably as it copies the .py files which I don't want to. I know that endswith requires 1-D variable or tuple to work.

Part of my script is given below:

x = os.getcwd()
ext_to_avoid = (".xml", ".bat", ".py", ".txt");
list_of_files_to_copy = []
for root, dirs, files in os.walk(x):
  for name in files:
    if not any([name.endswith(x) for x in ext_to_avoid]):
        print(os.path.join(root,name))
        list_of_files_to_copy.append(os.path.join(root,name))

I am not sure what's wrong with it. Could anyone point me to the right direction?

Kindest Reagrds,


Solution

  • You have many file extensions to check against. Since the function "endswith" accepts a single string as an argument, given a single name you need to test it against each ext:

    matches = False
    for ext in ext_to_avoid:
        if name.lower().endswith(ext):
            matches = True
            break
    if not matches:
        # ...
    

    A simpler one liner can be:

    if not any([name.lower().endswith(ext) for ext in ext_to_avoid]):
        # ...
    

    EDIT: Well, it seems that str.endswith will also accepts a tuple. Meaning that your original code was correct; try checking agains lowercase always:

    if not name.lower().endswith(ext_to_avoid):
        # ...