Skip to content

Instantly share code, notes, and snippets.

@niket-agrawal
Last active July 17, 2019 05:20
Show Gist options
  • Select an option

  • Save niket-agrawal/aa6ddbf3f8bf8b7f344325a916a02d81 to your computer and use it in GitHub Desktop.

Select an option

Save niket-agrawal/aa6ddbf3f8bf8b7f344325a916a02d81 to your computer and use it in GitHub Desktop.
[Python]__ Access all file types of particular extension from any directory path
import os
#used for accessing the particular folders
folders = ['Patient1', 'Patient2','Patient3']
#uncomment the following line to access all folders present in the directory
#folders = os.listdir("C:\\Users\\niket\\Desktop\\Download Dustbin\\main_folder")
def load_from_folder(folder):
images = []
sub_path = "C:\\Users\\niket\\Desktop\\Download Dustbin\\main_folder\\" + folder
for filename in os.listdir(sub_path):
if any([filename.endswith(x) for x in ['.jpg', '.jpeg']]):
tple = (folder, os.path.splitext(filename)[0])
images.append(tple)
return images
all_images = []
for folder in folders:
images = load_from_folder(folder)
for single_img in images:
all_images.append(single_img)
for file_img in all_images:
print(file_img)
print("Image",file_img[1]+'.jpg is in folder',file_img[0])
print("\nTotal images :",len(all_images))
@niket-agrawal

niket-agrawal commented Jul 17, 2019

Copy link
Copy Markdown
Author

[Python] - To access all files inside any particular directory

(Dependencies - os)
This code is mainly written for access of specific extension file type/s (.jpg in this case) inside any specific folder. The folder path must be supplied in sub_path variable, and list of folders to be accessed is to be supplied manually in folders variable.

Alternatively, you can also access all folders by un-commenting the folders variable access below.

How to Run -

  • for specific folders (inside any main_folder), just supply its list by manually entering the list.
  • for all folders, inside it, (comment line3 & uncomment line5). It will use Python's function os.listdir('path_to_be_supplied' ) to make list of all folders automatically inside the main folder.

Example of output
Input folder is main_folder

Directory tree
image

Output is :

Image img1.jpg is in folder Patient1
Image img2.jpg is in folder Patient1
Image img1.jpg is in folder Patient2
Image img1.jpg is in folder Patient3
Image img2.jpg is in folder Patient3
Image img3.jpg is in folder Patient3

Total images : 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment