如何在Python中按数字顺序从指定路径上传图片
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.walkdoesn't guarantee any consistent order for files—this ensures you get exactly the sequence you want every time. os.path.joininstead 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

