bananagator
bananagator

Reputation: 581

Check if list of file paths exist

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?

Upvotes: 1

Views: 2187

Answers (2)

Iain Shelvington
Iain Shelvington

Reputation: 32244

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

Upvotes: 0

smac89
smac89

Reputation: 43088

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)]

Upvotes: 2

Related Questions