简体   繁体   中英

Python Question Related to Folders and Files inside of the folders

I have a folder(Fruits) that contains both apple and orange images. Let's say fifty per each. And the folder contains total 100 images.

In this fruit folder, Apple images are held like apple0.jpg, apple1.jpg........ apple49.jpg

On the other hand, orange images are held like orange0.jpg, orange1.jpg, orange2.jpg........ orange49.jpg

So with that datas, how can I create a Apple file and copy all apple images there. Not only this, but also, how can I create Orange file and copy all the orange images to that Orange file.

I'm using Python programming language. Is there any tutorial about this, or do you have any idea how can I perform this.

Thank you for all of your comments. I am planning to do these in Google colab.

Assuming you mean you want to create a new folder Apples and Oranges to move the files in, if the files can be relied to start with apple or oranges, you can use the following simple bruteish code:-

import os
import shutil

files = os.listdir('Fruits')

if not os.path.isdir('Oranges'):
  os.mkdirs('Oranges')

if not os.path.isdir('Apples'):
  os.mkdirs('Apples')

for f in files:
  if not f.endswith('.jpg'):
    continue
  
  if f.startswith('apple'):
    target = os.path.join('Apples', f)
  elif f.startswith('orange'):
    target = os.path.join('Oranges', f)
   
  shutil.move(os.path.join('Fruits', f), target)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM