简体   繁体   中英

Is there a way to sort the files in a directory in lexicographical order?

I'm trying to sort the files in the directory in lexicographical order and no matter what I've tried, it still returns is as if I've never sorted it.

  def directory(file_input):
 """Returns all files in the directory."""

    files = []
    pathway = Path(file_input)
    for file in pathway.iterdir():
        files.append(file)
    for file in sorted(files):
        search_contents_list.append(file)
        print(file)

os.listdir() alphabetizes its output by default (on my machine, anyway). If you're still not sure, then you can try sorted(os.listdir(), key=lambda s:s.lower()) to sort case-insensitively or by whatever criteria you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM