Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort files by size within a directory

I have four files a.jpg (5kb), b.jpg (1Kb), c.jpg (3Kb). Currently, they appear within a directory sorted by their names (Windows file explorer: Sort by -> Name). I want to use Python to sort them based on their size and reflect the change in the file explorer as well not just within the script.
I used ChatGPT to arrive at:

import os

def sort_files_by_size(directory):
    # Get a list of files in the directory
    files = os.listdir(directory)

    # Create a list of tuples where each tuple contains the filename and its size
    file_sizes = [(file, os.path.getsize(os.path.join(directory, file))) for file in files]

    # Sort the list of tuples based on the second element (file size)
    sorted_files = sorted(file_sizes, key=lambda x: x[1])

    # Display the sorted files
    for file, size in sorted_files:
        print(f"{file}: {size} bytes")

    # Optionally, you can move or rename the files based on the sorted order
    for index, (file, _) in enumerate(sorted_files, start=1):
        new_name = f"{file}"
        os.rename(os.path.join(directory, file), os.path.join(directory, new_name))

# Replace 'your_directory_path' with the actual path to your directory
directory_path = 'images'
sort_files_by_size(directory_path)

But the files in the explorer are still sorted by their names. Any leads?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As you correctly noticed File Explorer uses it’s own sorting logic when ever you open that directory. So you can’t just override that how ever you want. Well, not easily at least.

I can offer 2 hacks though:

  1. Use you ChatGPT code, and modify it to rename the files to
    01-Largest, 02-SecondLargest etc…

  2. Or just ditch your Python script and configure File Explorer. Check this
    How to set default sorting logic

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading