I have a list of file paths. I need to check which of the files in the list exist and which are not. I want to delete the paths that do not exist. I know i can use os.path.exists() or os.path.isfile() but for these I need to run a for loop and check each path in the list. Is there a better way to do this in python?
Asked
Active
Viewed 1,633 times
1
-
3whats wrong with for loop now? – dejanmarich Nov 30 '19 at 01:34
-
nothing's wrong with for loop i just want to know if there is another way. I dont know why would you downvote for that. – bananagator Nov 30 '19 at 01:36
-
if you're worried about performance, maybe just check the existence of a path right before you use it. unless you need to make sure that ALL of paths exist before you execute any code, to avoid half-deployed stuff. maybe look into list comprehensions. https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops – ingernet Nov 30 '19 at 01:36
-
Are all of the paths in the same folder? – Iain Shelvington Nov 30 '19 at 01:38
-
yes all the paths are in the same folder. – bananagator Nov 30 '19 at 01:39
-
1You need to define "better" here. What is it you want to improve on the solution you already seem to have? – juanpa.arrivillaga Nov 30 '19 at 01:43
2 Answers
2
I'm assuming you are trying to delete the files from the list not from the os
You can do this with a list comprehension:
files = [...] # list of file paths
files = [path for path in files if os.path.exists(path)]

smac89
- 39,374
- 15
- 132
- 179
-
1If the OP is worried about performance, then set is likely to be a bit more performant than a list - especially if their are many paths to check. – Tony Suffolk 66 Nov 30 '19 at 02:00
0
If all paths are within the same folder you can retrieve all files that exist in the folder in one call to os.listdir
then you can use set operations to get all paths in your list that exist in the
directory
files_in_dir = set(os.listdir(PATH))
existing_files = set(your_list_of_files) & files_in_dir

Iain Shelvington
- 31,030
- 3
- 31
- 50