gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Modify "random_background = random.choice(os.listdir(directory))" Python code to choose…
- User
Modify "random_background = random.choice(os.listdir(directory))" Python code to choose only from png, jpg, jpeg, jpeg xl and webp format files.
- Assistant
You can modify your code to filter for specific file formats when selecting a random file from the directory. Below is an example of how to achieve this:
pythonimport os import random directory = 'your_directory_path_here' # Replace with your directory path # List of allowed file extensions allowed_extensions = ('.png', '.jpg', '.jpeg', '.jxl', '.webp') # Get only files with the allowed extensions valid_files = [file for file in os.listdir(directory) if file.lower().endswith(allowed_extensions)] # Select a random background if there are valid files if valid_files: random_background = random.choice(valid_files) print(random_background) else: print("No valid image files found in the directory.")