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

如何在Python中按数字顺序从指定路径上传图片

How to Load Images in Sequential Order (0001.jpg, 0002.jpg, ...)

Hey there! The problem you're running into is that os.walk() returns files in the order your filesystem stores them, which isn't guaranteed to match your desired sequential order. To fix this, you just need to explicitly sort the file list before processing each one. Here's how to adjust your code:

Basic Solution (Fixed-Digit Filenames)

If your filenames always use the same number of leading zeros (like 0001.jpg, 0002.jpg), a simple lexicographical sort will work perfectly. Just sort the files list before iterating:

import os
from PIL import Image

for subdirs, dirs, files in os.walk(args.imagesdirectory):
    # Sort files to enforce sequential order
    sorted_files = sorted(files)
    for file in sorted_files:
        print("file is ", file)
        # Use os.path.join for cross-platform path compatibility (better than manual string concatenation)
        path = os.path.join(subdirs, file)
        print("path is ", path)
        img = Image.open(path)

Quick Tips:

  • Why sort? os.walk doesn't guarantee any consistent order for files—this ensures you get exactly the sequence you want every time.
  • os.path.join instead of /: This works seamlessly on Windows, macOS, and Linux without worrying about path separator differences.

Advanced Solution (Variable-Digit Filenames)

If your filenames might have variable leading zeros (e.g., 1.jpg, 10.jpg, 002.jpg), a simple string sort will incorrectly place 10.jpg before 2.jpg. To fix this, extract the numeric part of the filename and sort by that integer value:

import os
import re
from PIL import Image

def get_numeric_key(filename):
    # Extract the numeric prefix from .jpg filenames
    match = re.search(r'^(\d+)\.jpg$', filename)
    if match:
        return int(match.group(1))
    # Push non-matching files to the end of the sorted list
    return float('inf')

for subdirs, dirs, files in os.walk(args.imagesdirectory):
    # Sort using the numeric value of the filename's prefix
    sorted_files = sorted(files, key=get_numeric_key)
    for file in sorted_files:
        print("file is ", file)
        path = os.path.join(subdirs, file)
        print("path is ", path)
        img = Image.open(path)

This function pulls out the number from each filename, converts it to an integer, and uses that as the sorting key—so 2.jpg will always come before 10.jpg, regardless of leading zeros.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:58:34