Process files in order

K

Khoa Nguyen

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
 
Y

Yu-Xi Lim

Khoa said:
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().
 
M

Mike Kent

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

Bruno Desthuilliers

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
 
B

bearophileHUGS

A possibility:

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

Bye,
bearophile
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top