Find a file in specific folders in Python


I have 5 folders, 1,2,3,4,5. I want to know which folders don’t have the file Data.csv in them. Is there a straightforward way to do it?

for i in range(1,N+1):
    file_loc = f"C:\Users\{i}\Data.csv"
Asked By: user19977266



You can use os.path.exists to check if the provided path exists or not. Also on a side note, instead of manually adding \ in the path, you can use os.path.join

import os
for i in range(1,N+1):
    file_loc = os.path.join("C:\", "Users", str(i), "Data.csv")
    if not os.path.exists(file_loc):
Answered By: ThePyGuy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.