Answer a question

I am trying 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

Answers

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).

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐