You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中os.scandir为何不按顺序扫描?图片排序求助

Fixing Numeric Sorting for Your Image Files

Ah, I’ve run into this exact issue before—lexicographical sorting vs. numeric sorting trips up a lot of people! The problem is that when you list files normally, your system sorts them as strings, so "img(10)" comes before "img(2)" because the character '1' is alphabetically before '2'. Here’s how to fix it properly:

Step-by-Step Solution Using Python

Python makes this straightforward because we can extract the numeric part of each filename and use that as the sort key. Here’s a complete script that will do exactly what you need:

import os

# Replace this with your actual photo directory path
photo_dir = "/path/to/your/photos"

# Filter to get only files matching the img(n) pattern
image_files = [f for f in os.listdir(photo_dir) if f.startswith("img(") and f.endswith(")")]

# Function to pull the numeric ID from the filename
def extract_image_id(filename):
    # Grab the part between parentheses and convert to integer
    return int(filename.split("(")[1].split(")")[0])

# Sort the files using the numeric ID as the key
sorted_images = sorted(image_files, key=extract_image_id)

# Create full file paths and write to a text file
full_paths = [os.path.join(photo_dir, img) for img in sorted_images]
with open("sorted_image_paths.txt", "w") as output_file:
    output_file.write("\n".join(full_paths))

Script Breakdown:

  • Filtering Files: We first narrow down to only files that follow the img(n) naming rule to avoid including unrelated files.
  • Extracting Numeric IDs: The extract_image_id function pulls the number inside the parentheses and converts it to an integer—this is what we’ll use for sorting.
  • Numeric Sort: The sorted() function uses our custom key to order files by their actual numeric ID, not the string version.
  • Writing Paths: We combine each filename with the directory path to get full paths, then write them one per line to sorted_image_paths.txt.

Alternative: Using the natsort Library (Simpler)

If you don’t mind installing a third-party library, natsort handles natural/numeric sorting out of the box. First install it with pip install natsort, then use this shorter script:

import os
from natsort import natsorted

photo_dir = "/path/to/your/photos"
image_files = [f for f in os.listdir(photo_dir) if f.startswith("img(") and f.endswith(")")]
sorted_images = natsorted(image_files)

full_paths = [os.path.join(photo_dir, img) for img in sorted_images]
with open("sorted_image_paths.txt", "w") as output_file:
    output_file.write("\n".join(full_paths))

natsorted() automatically detects numeric parts in strings and sorts them correctly, so you don’t have to write custom extraction logic.

Either approach will give you the exact order you need: img(0), img(1), img(2), ..., img(1599). Just make sure to replace /path/to/your/photos with your actual directory path.

内容的提问来源于stack exchange,提问作者Furin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:25:57