By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,919 Members | 1,074 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,919 IT Pros & Developers. It's quick & easy.

Process files in order

P: n/a
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
Jul 27 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a
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().
Jul 27 '06 #2

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

Jul 27 '06 #3

P: n/a
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(getcwd())
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
Jul 27 '06 #4

P: n/a
A possibility:

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

Bye,
bearophile

Jul 27 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.