0

I want to delete several files which do not have the appropriate file extension (here .txt) from a dictionary. I intend to achieve this without using a for loop, but my implementation, which uses a combination of lambda and map function, for some reason does not delete the files. What am I doing wrong?

Code version without for loop (does not work):

files = next(os.walk(data_filepath))[2]
files_wrong_extension = list(filter(lambda x: not x.endswith(".txt"), files))
map(lambda x: os.remove(data_filepath + "/" + x), files_wrong_extension)
logger.info(f"{files_wrong_extension} were removed since they do not have a '.txt' file extension")

Code version with a for loop (works):

files = next(os.walk(data_filepath))[2]
files_wrong_extension = list(filter(lambda x: not x.endswith(".txt"), files))
for file in files_wrong_extension:
   os.remove(data_filepath + "/" + file)
   logger.info(f"{files_wrong_extension} were removed since they do not have a '.txt' file extension")
pa1ric6
  • 39
  • 6
  • 1
    "I intend to achieve this without using a for loop" Why? What's wrong with using the loop? – Karl Knechtel Jul 07 '22 at 08:11
  • 1
    [This answer](https://stackoverflow.com/a/1303354/4177009) looks relevant. Besides, functional-programming purists will tell you that using `map` for side effects is bad form; an explicit `for` loop is the way to go. – Ture Pålsson Jul 07 '22 at 08:14
  • Thanks a lot @TurePålsson for the explanation. Then I'll stick to the `for` loop. – pa1ric6 Jul 07 '22 at 10:07
  • @KarlKnechtel there is nothing wrong with using a for loop. I was just curious how this functionality could be implemented without using one and did/do not really understand why my combination of map and lambda function does not do the trick. – pa1ric6 Jul 07 '22 at 10:12
  • Please see the linked duplicate, then. `map` doesn't evaluate anything up front. It used to in 2.x, but that comes with its own set of problems. – Karl Knechtel Jul 07 '22 at 17:45

0 Answers0