开发者

Find the newest folder in a directory in Python

I am t开发者_如何学Crying to have an automated script that enters into the most recently created folder.

I have some code below

import datetime, os, shutil 

today = datetime.datetime.now().isoformat() 
file_time = datetime.datetime.fromtimestamp(os.path.getmtime('/folders*')) 

if file_time < today: 
    changedirectory('/folders*') 

I am not sure how to get this to check the latest timestamp from now. Any ideas?

Thanks


There is no actual trace of the "time created" in most OS / filesystems: what you get as mtime is the time a file or directory was modified (so for example creating a file in a directory updates the directory's mtime) -- and from ctime, when offered, the time of the latest inode change (so it would be updated by creating or removing a sub-directory).

Assuming you're fine with e.g. "last-modified" (and your use of "created" in the question was just an error), you can find (e.g.) all subdirectories of the current directory:

import os

all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]

and get the one with the latest mtime (in Python 2.5 or better):

latest_subdir = max(all_subdirs, key=os.path.getmtime)

If you need to operate elsewhere than the current directory, it's not very different, e.g.:

def all_subdirs_of(b='.'):
  result = []
  for d in os.listdir(b):
    bd = os.path.join(b, d)
    if os.path.isdir(bd): result.append(bd)
  return result

the latest_subdir assignment does not change given, as all_subdirs, any list of paths (be they paths of directories or files, that max call gets the latest-modified one).


One liner to find latest

# Find latest
import os, glob
max(glob.glob(os.path.join(directory, '*/')), key=os.path.getmtime)

One liner to find n'th latest

# Find n'th latest
import os, glob
sorted(glob.glob(os.path.join(directory, '*/')), key=os.path.getmtime)[-n]


And a quick one-liner:

directory = 'some/path/to/the/main/dir'
max([os.path.join(directory,d) for d in os.listdir(directory)], key=os.path.getmtime)


Python Version 3.4+

We can try pathlib and the solution will be one liner

Find latest

import pathlib
max(pathlib.Path(directory).glob('*/'), key=os.path.getmtime)

To get nth latest

import pathlib
sorted(pathlib.Path(directory).glob('*/'), key=os.path.getmtime)[-n]


here's one way to find latest directory

import os
import time
import operator
alist={}
now = time.time()
directory=os.path.join("/home","path")
os.chdir(directory)
for file in os.listdir("."):
    if os.path.isdir(file):
        timestamp = os.path.getmtime( file )
        # get timestamp and directory name and store to dictionary
        alist[os.path.join(os.getcwd(),file)]=timestamp

# sort the timestamp 
for i in sorted(alist.iteritems(), key=operator.itemgetter(1)):
    latest="%s" % ( i[0])
# latest=sorted(alist.iteritems(), key=operator.itemgetter(1))[-1]
print "newest directory is ", latest
os.chdir(latest)


import os, datetime, operator

dir = "/"
folders = [(f,os.path.getmtime('%s/%s'%(dir,f))) for f in os.listdir(dir) if os.path.isdir(f)]
(newest_folder, mtime) = sorted(folders, key=operator.itemgetter(1), reverse=True)[0]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜