Python code to manage image files in a directory: "Maintain a designated number of images within a directory by using Python to

In my dataset, I have three main folders named Train, Test, and Val. Each of these folders contains over 100 subfolders. My goal is to only keep a maximum of 90 images in each folder. If a particular subfolder has more than 90 images, I need to delete the extra images.

| dataset
|   | 
|   | Train
|   |   |
|   |   | Folder (1 of 112)
|   |   |   |
|   |   |   | Images  
 

Answer №1

Below is a concise example that showcases how to manipulate files in Python:

import os 

if __name__ == "__main": 

for (root,dirs,files) in os.walk('.', topdown=True): 

    print (root) 

    print (dirs) 

    print (files) 

    print ('--------------------------------') 

In this code snippet, you can input the path you want to search for and retrieve the files stored at that location as a tuple of filenames. You can determine the number of files found by using the len() function. If the count exceeds 90, an if statement will remove all files above index 90.

file_length=len(files)
if file_length>90:
    for i in range(91,file_length):
        os.remove(files[i])

The code snippet also demonstrates how to properly delete files using the os.remove() function within a loop. It is important to ensure the correct path is specified before deleting a file, such as using os.remove("images//"+files[i]) within the loop when targeting files within the images directory.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "No module named Image" is indicating that there is a missing module in the specified file path build/exe.win-amd64-3.6/scipy/misc

I am working on a Python application for image processing that will be compiled into an EXE file. My tools of choice are tkinter and cx_Freeze. However, I have encountered an error during the process. https://i.stack.imgur.com/ThRs4.jpg Below is the con ...

Looping through conditions in the Python Rock Paper Scissors game

My Rock Paper Scissors program needs a specific condition added to it. I want the user to play continuously until either they or the computer wins more than two times in a row. I've searched high and low for the solution, but unfortunately, I haven&ap ...

an alternative for checking if the script is being run as the main program:

I have a main.py file along with a module called gui.py. My goal is to compile them to Cython and then create an executable which includes the following code: import gui if __name__ == '__main__': gui() In the gui.py module, I have some cod ...

Tips for preserving leading zeros during the conversion process from XML to CSV

I have encountered an issue with my code. When I view the DateTime in the XML file, it is 01052022000000000, but when I try to access it using Python, it appears as 1052022000000000 (the left zero is missing). I attempted to resolve this by using the func ...

Click on a previously saved Selenium element once the page has been reloaded

Is there a way to achieve a similar functionality where each "button" press triggers a page reload? element = driver.find_element_by_xpath("//select[@name='name']") all_options = element.find_elements_by_tag_name("option") for option in all_opti ...

Error encountered: Element not clickable - The attempt to click on a download link was interrupted due to the element being intercepted

When using Selenium and Python, I am working on automating the process of clicking on targets.simple.csv to download a .csv file from the following page: This is the code snippet I have written: import pandas as pd import numpy as np from datetime import ...

Adding from the iteration of the past loop in Python

I am encountering a simple yet frustrating issue. Each time I read in a list of file names stored in an ascii file ("file_input.txt") and perform calculations on them, the output from the calculation ("print peak_wv, peak_flux" in the script below) keeps ...

I am looking for the C# counterpart of hexdigest function used in Python 3.2. Can anyone help me with

Currently, I am in the process of transitioning a Python 3.2 program to C#. Within the Python program, there is a line of code that returns a string object with double the length, consisting solely of hexadecimal digits. The specific snippet from the Pyt ...

What is the most effective way to manage multiple .find() checks within an if statement with grace?

Currently, my code has a lengthy line with multiple value checks that is becoming too cumbersome. How can I simplify it? if string.find(a) != -1 and string.find(b) != -1 string.find(b) != -1 and string.find(c)==-1 and string.find(d)==-1 string not in list: ...

Exporting table data to a CSV file using Selenium and Python

My goal is to automate the process of extracting my transcript data and saving it to a CSV file using Python with Selenium. I've managed to automate reaching the table page, however, I am facing an issue where only the first row of the table is displa ...

Tips for generating skipgrams utilizing Python

When it comes to skipgrams, they are considered to be ngrams that encompass all ngrams and include each (k-i)skipgram until (k-i)==0 (which covers 0 skip grams). So, the question arises: how can one efficiently calculate these skipgrams in Python? Below i ...

Listing and Organizing Lists

I'm currently trying to grasp the concept of a code snippet I found in an online tutorial. Within this code, there is an instance where questions_int is represented as a list consisting of nested lists with numerical values structured like so: [[721 ...

Group JSON data in Python based on the individuals' last names

Hey there, I'm new to this. How can I manipulate a Json data in Python to create a new format where the last name is used as the key and the value contains the total count of people with the same last name, along with their respective age and departme ...

Calling NVIDIA Performance Primitives in Python: A Comprehensive Guide

How can we utilize the NVIDIA Performance Primitives (NPP) library in Python? ...

Python chatbot delivers interactive message with clickable options

My goal is to send a message using a telegram bot with buttons. When a button is pressed, I want to identify which button was clicked and then change the text that corresponds to that button. I have managed to figure out how to do these tasks separately b ...

Unable to fetch any links through the driver.find_elements method using the href attribute

As a newcomer to Python and Selenium WebDriver, my goal is to verify all links on my webpage by checking their HTTP status codes to identify any broken links. The snippet of code I am currently using looks like this... from selenium import webdriver from ...

The Tensorflow model appears to have difficulty fully erasing itself and continues to take up space in the CPU memory

Currently, I am focused on optimizing the neural network architecture and hyperparameters. To achieve this, I have created a for loop to iterate through different sets of hyperparameters, build/train/evaluate a new model in each iteration. The code snippet ...

Is it incorrect to run the script multiple times in order for it to function properly?

After attempting to execute this script using both a while loop and a for loop, I noticed that it stops working after just one repetition. driver.find_element_by_class_name("submit").click() x = driver.find_element_by_class_name("submit" ...

Execute Stealthy Selenium Browser

Currently, I am utilizing the Selenium library which opens a browser when it runs. The browser displays all the links that are being accessed. However, my goal is to have the Selenium driver run in a hidden browser mode so that the user is unaware that we ...

Selenium paired with the innovative Brave browser, a Chromium-based platform with the latest Version 1.33.106 Chromium: 96.0.4664.110 (Official Build) (64-bit)

I have just started learning Python and am currently working on a browser automation project using Selenium. Currently, I am using Brave version 96.0.4664.45 but facing issues with my Chrome driver not functioning properly. On the other hand, geckodriver i ...