<jupyter_start><jupyter_text>How process files in a folderSee also* [Working with files in python](https://realpython.com/working-with-files-in-python/)* [Iterate over files in a directory](https://newbedev.com/how-to-iterate-over-files-in-a-given-directory)<jupyter_code>import os

# define the location of the folder to go through
directory = '../data/beads/'

# get a list of files in that folder
file_list = os.listdir(directory)

file_list<jupyter_output><empty_output><jupyter_text>Obviously, there are not just images in that folder. Let's filter the list:<jupyter_code>image_file_list = [file for file in file_list if file.endswith(".tif")]

image_file_list<jupyter_output><empty_output><jupyter_text>Alternatively, we can also write a longer for-loop and check if files are images:<jupyter_code># go through all files in the folder
for file in file_list:
    # if the filename is of a tif-image, print it out
    if file.endswith(".tif"):
        print(file)<jupyter_output>243.tif
245.tif
271.tif
277.tif<jupyter_text>In order to show all images, we need to open them from the correct `directory`:<jupyter_code>from skimage.io import imread
from matplotlib.pyplot import imshow, show

# go through all files in the folder
for image_file in image_file_list:
    image = imread(directory + image_file)
    imshow(image)
    show()<jupyter_output><empty_output><jupyter_text>[Custom functions](https://nbviewer.jupyter.org/github/BiAPoL/Bio-image_Analysis_with_Python/blob/main/python_basics/09_custom_functions.ipynb) help us to keep code organized. For example, we can put image-analysis code in a function and then just call it:<jupyter_code>from skimage.io import imread
import numpy as np

def load_and_measure(filename):
    """
    This function opens an image and returns its mean intensity.
    """
    image = imread(filename)
    
    # return mean intensity in the image
    return np.mean(image)

# for testing
load_and_measure(directory + "277.tif")<jupyter_output><empty_output><jupyter_text>With such a custom function, we can make use of short for-loops:<jupyter_code>mean_intensities_of_all_images = [load_and_measure(directory + file) for file in image_file_list]
mean_intensities_of_all_images<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08977777777777778, 'fraction_numerical': 0.007555555555555556, 'mean_word_length': 5.376770538243626, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 24, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '408634', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 762, 'n_tokens_neox': 728, 'n_words': 212, 'path': 'docs/33_batch_processing/12_process_folders.ipynb', 'repo_name': 'zoccoler/BioImageAnalysisNotebooks', 'size': '2250'}