Process files in order

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Khoa Nguyen

    #1

    Process files in order

    Hi,

    I have a requirement to process all files in a directory in
    chronological order. The os.listdir() function, however, lists the
    files in random order. Is there a similar function in Python that
    allows me to specify the listing order (like ls -t for example)?

    Thanks,
    Khoa
  • Yu-Xi Lim

    #2
    Re: Process files in order

    Khoa Nguyen wrote:
    I have a requirement to process all files in a directory in
    chronological order. The os.listdir() function, however, lists the
    files in random order. Is there a similar function in Python that
    allows me to specify the listing order (like ls -t for example)?
    There is no single command, but you can easily sort the results of
    listdir using any criteria. Most file attributes can can be obtained
    using os.stat (size, creation date, modification date, etc), and you can
    just use that as a key to sort().

    Comment

    • Mike Kent

      #3
      Re: Process files in order

      How about using os.listdir to build a list of filenames, then sorting
      them by modification time (via os.stat)?

      Comment

      • Bruno Desthuilliers

        #4
        Re: Process files in order

        Khoa Nguyen a écrit :
        Hi,
        >
        I have a requirement to process all files in a directory in
        chronological order.
        Access time, modification time ? Ascending, descending ?-)
        The os.listdir() function, however, lists the
        files in random order. Is there a similar function in Python that
        allows me to specify the listing order (like ls -t for example)?
        Not AFAIK. But os.path.get[acm]time(<filename> ) and sorted() may help:

        from os.path import getmtime, join, isfile
        from os import listdir, getcwd

        listfiles = lambda p: filter(isfile, # only list files
        map(lambda f, p=p : join(p,f),
        listdir(p)))

        files = listfiles(getcw d())
        sortedfiles = map(lambda item: item[1],
        sorted(zip(map( getmtime, files), files)))


        You can apply reversed() to sortedfiles if you want them in reversed order.


        HTH

        Comment

        • bearophileHUGS@lycos.com

          #5
          Re: Process files in order

          A possibility:

          import os
          _, _, file_names = os.walk("").nex t()
          print sorted(file_nam es, key=lambda fn: os.stat(fn)[8])

          Bye,
          bearophile

          Comment

          Working...