Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the os.path.exists() function to check if a file exists before importing it in a loop. Here is an example:

import os

for i in range(10):
    filename = f"data_{i}.txt"
    if os.path.exists(filename):
        with open(filename, "r") as f:
            # do something with the file
    else:
        print(f"{filename} does not exist")

This code will loop through files "data0.txt" to "data9.txt" and check if each file exists before opening it. If the file does not exist, it will print a message to the console.