How to Sort Files by Number in Name Using Python?

Estimated read time 2 min read

To sort files by number in name using Python, you can follow these steps:

  1. Use the glob module to obtain a list of filenames in the directory you want to sort.
  2. Use the sorted function to sort the list of filenames.
  3. Use a lambda function as the key argument for the sorted function. The lambda function will extract the number from the filename and use it as the sorting key.
  4. Finally, iterate over the sorted list of filenames and process each file as desired.

Here’s an example implementation:

import glob

# Obtain a list of filenames in the directory
filenames = glob.glob("path/to/directory/*.txt")

# Sort the filenames by number in name
sorted_filenames = sorted(filenames, key=lambda x: int(x.split("_")[1]))

# Process each file in the sorted list
for filename in sorted_filenames:
    # Do something with the file

In this example, we assume that the filenames have a pattern of prefix_number.txt, where prefix is some fixed string and number is the number that we want to sort by. We split the filename on the underscore character and extract the second element (which corresponds to the number) as an integer using the int function. We then use this integer as the sorting key for the sorted function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply