Python3 os.listdir() output file order
os.listdir(path):
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
Order cannot be relied upon and is an artifact of the filesystem.
To sort the result, use sorted(os.listdir(path))
.
import os for count, filename in enumerate(sorted(os.listdir(path)), start=1): print('Enter {} to select {}'.format(count, filename))
from stat import S_ISREG, ST_CTIME, ST_MODE import os, sys, time #Relative or absolute path to the directory dir_path = sys.argv[1] if len(sys.argv) == 2 else r'.' #all entries in the directory w/ stats data = (os.path.join(dir_path, fn) for fn in os.listdir(dir_path)) data = ((os.stat(path), path) for path in data) # regular files, insert creation date data = ((stat[ST_CTIME], path) for stat, path in data if S_ISREG(stat[ST_MODE])) for cdate, path in sorted(data): print(time.ctime(cdate), os.path.basename(path))
Reference
https://docs.python.org/3/library/os.html#os.listdir
https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir
https://www.reddit.com/r/learnpython/comments/3xg6ba/help_making_oslistdir_return_items_in_order/
https://www.w3resource.com/python-exercises/python-basic-exercise-71.php
posted on 2018-10-19 10:39 Quinn-Yann 阅读(316) 评论(0) 编辑 收藏 举报