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.
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
Asked: 2023-06-06 17:41:11 +0000
Seen: 21 times
Last updated: Jun 06 '23
How can I transfer .avi video files to Unity?
How to access HTML files stored on Google Drive?
What is the process for opening e57 files in C#?
Why are the files I uploaded not visible on the Windows Android Emulator?
How can I install Beegfs on Ubuntu 22.04?
How can a .zip file from GitHub be loaded into Google Colab?
What is the process of using the Multmerge() function in r to combine files in a directory?