Python traverses files by natural number Python Os.listdir sort by natural sorting

Source: Internet
Author: User

ImportOSImportRedefsorted_aphanumeric (data): Convert=LambdaText:int (text)ifText.isdigit ()Elsetext.lower () Alphanum_key=LambdaKey: [Convert (c) forCinchRe.split ('([0-9]+)', Key)] returnSorted (data, key=alphanum_key) file= Sorted_aphanumeric (Os.listdir ("./2")) forFinchFile:Print(f)

Reference

Https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir

Python for whatever reason does no come with a built-in a-to has natural sorting (meaning 1, 2, instead of 1, ten, 2), so you had to write it yourself:

ImportReDefSorted_aphanumeric(Data):Convert= LambdaText:Int(Text) IfText.IsDigit() ElseText.Lower() Alphanum_key = lambda Key:  [ Convert (c   for C in  Re. ( ([0-9]+) ' , Key )  ] return Sorted (data, Key= alphanum_key)            

You can now use the This function to sort a list:

dirlist = sorted_aphanumeric(os.listdir(...))

Python traverses files by natural number Python Os.listdir sort by natural sorting

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.