You need to create a Python script that generates 40 CSV files. Each CSV file should…
- User
You need to create a Python script that generates 40 CSV files. Each CSV file should contain a shuffled list of 212 filenames. The filenames will be selected from a directory containing exactly 192 images. Additionally, 20 random filenames should be added to each CSV file. The CSV files should be saved in the same directory and named "observer_1.csv" to "observer_40.csv". The filenames should follow the format "images/47.jpg", "images/52.jpg", "images/33.jpg", and so on.
- Assistant
You can use the following Python script to achieve this task:
import os import random import csv # Constants IMG_DIR = "images" # Directory containing image files OUT_DIR = "output" # Directory to output CSV files NUM_FILES = 40 # Number of CSV files to generate NUM_IMAGES = 192 # Number of images in the image directory NUM_EXTRA = 20 # Number of extra random filenames to add per CSV IMG_EXT = ".jpg" # Image file extension # Get a list of filepaths for all images in the image directory filepaths = [os.path.join(IMG_DIR, str(i) + IMG_EXT) for i in range(1, NUM_IMAGES + 1)] # Create the output directory if it doesn't exist if not os.path.exists(OUT_DIR): os.makedirs(OUT_DIR) # Generate and save each CSV file for i in range(NUM_FILES): # Shuffle the filepaths random.shuffle(filepaths) # Add extra random filenames new_list = filepaths.copy() for j in range(NUM_EXTRA): new_list.append(IMG_DIR + "/" + str(random.randint(1, NUM_IMAGES)) + IMG_EXT) # Write new shuffled and expanded list to a CSV file with open(os.path.join(OUT_DIR, "observer_" + str(i + 1) + ".csv"), "w", newline='') as csvfile: writer = csv.writer(csvfile) for row in new_list: writer.writerow([row]) print("CSV files generated successfully.")