Ask Your Question
4

How can I avoid importing non-existent data files in a loop?

asked 2023-06-06 17:41:11 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-06 17:58:02 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 17:41:11 +0000

Seen: 21 times

Last updated: Jun 06 '23