Reputation: 101
I have a list of colors with a txt file containing URLs of images of those colors. I am trying to create a folder to contain images of each color and move this directory so that I may ultimately download the images.
I am able to perform this for each element of the list individually, but this is tedious and I would prefer to automate it.
classes = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
This is the code I currently have for each color:
folder = 'red'
file = 'red.txt'
mv red.txt data/colors
path = Path('data/colors')
dest = path/colors
dest.mkdir(parents=True, exist_ok=True)
download_images(path/file, dest, max_pics=200)
I expect to have a folder per color containing the respective downloaded images.
Upvotes: 1
Views: 1570
Reputation: 61
Your list of colors is in classes
python list. You have <color name>.txt
files containing URLs of images of those colors listed in classes
list. So you have an initial directory structure which looks like following directory tree:
.
├── blue.txt
├── green.txt
├── orange.txt
├── purple.txt
├── red.txt
├── script.py
└── yellow.txt
Now you want to create separate directories for each color. So finally your directory structure should look like following directory tree:
.
├── data
│ └── colors
│ ├── blue
│ ├── blue.txt
│ ├── green
│ ├── green.txt
│ ├── orange
│ ├── orange.txt
│ ├── purple
│ ├── purple.txt
│ ├── red
│ ├── red.txt
│ ├── yellow
│ └── yellow.txt
└── script.py
Where your download_image()
method will download the image for given URLs in <color name>.txt
file which it receives as one of the arguments. It also receives the destination of the image directory to be placed and the maximum no of images it should download.
If I understood your problem correctly following code would solve your problem. Code is well commented and self-explanatory. You can drop comments to ask for more clarifications.
import os
base_path = "data/colors/"
# create base path directories if not already present
os.system("mkdir -p data")
os.system("mkdir -p data/colors")
classes = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
# dummy download image function
def download_image(path, dest, max_pics):
print("URL file path: " + path)
print("Image destination: " + dest)
print("No of Images to be downloaded: " + str(max_pics))
if __name__ == "__main__":
for colour in classes:
# create directories for each colour if not already present
os.system("mkdir -p " + base_path + colour)
# move <colour_name>.txt file into base path
os.system("mv " + colour+".txt " + base_path)
dest = base_path + colour
# call download_image method
download_image(base_path+colour+".txt", dest, max_pics=200)
Upvotes: 1