How to Get a List of Files in a Folder in Which the Files Are Sorted with Modified Date Time

How do you get a directory listing sorted by creation date in python?

Update: to sort dirpath's entries by modification date in Python 3:

import os
from pathlib import Path

paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)

(put @Pygirl's answer here for greater visibility)

If you already have a list of filenames files, then to sort it inplace by creation time on Windows (make sure that list contains absolute path):

files.sort(key=os.path.getctime)

The list of files you could get, for example, using glob as shown in @Jay's answer.


old answer
Here's a more verbose version of @Greg Hewgill's answer. It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on Windows).

#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time

# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)

# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
for stat, path in entries if S_ISREG(stat[ST_MODE]))
#NOTE: on Windows `ST_CTIME` is a creation date
# but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date

for cdate, path in sorted(entries):
print time.ctime(cdate), os.path.basename(path)

Example:

$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py

Best way to list files in Java, sorted by Date Modified?

I think your solution is the only sensible way. The only way to get the list of files is to use File.listFiles() and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a Comparator that uses File.lastModified() and pass this, along with the array of files, to Arrays.sort().

How to get the list of csv files in a directory sorted by creation date in Python

You could try using os.scandir:

from os import scandir

def get_sort_files(path, file_extension):
"""Return the oldest file in path with correct file extension"""
list_of_files = [(d.stat().st_ctime, d.path) for d in scandir(path) if d.is_file() and d.path.endswith(file_extension)]
return min(list_of_files)

os.scandir seems to used less calls to stat. See this post for details.
I could see much better performance on a sample folder with 5000 csv files.

How to get N files in a directory order by last modified date?

  • Limit just some files => pipe to Select-Object -first 10
  • Order in descending mode => pipe to Sort-Object LastWriteTime -Descending
  • Do not list directory => pipe to Where-Object { -not $_.PsIsContainer }

So to combine them together, here an example which reads all files from D:\Temp, sort them by LastWriteTime descending and select only the first 10:

Get-ChildItem -Force -Recurse -File -Path "C:\Users" -ErrorAction SilentlyContinue | Where-Object { $_.CreationTime.Date -lt (Get-Date).Date } | Sort CreationTime -Descending | Select-Object -First 10 CreationTime,FullName | Format-Table -Wrap 

How to get a list of files in a folder in which the files are sorted with modified date time?

Most operating systems do not return directory entries in any particular order. If you want to sort them (you probably should if you are going to show the results to a human user), you need to do that in a separate pass. One way you could do that is to insert the entries into a std::multimap, something like so:

namespace fs = boost::filesystem;
fs::path someDir("/path/to/somewhere");
fs::directory_iterator end_iter;

typedef std::multimap<std::time_t, fs::path> result_set_t;
result_set_t result_set;

if ( fs::exists(someDir) && fs::is_directory(someDir))
{
for( fs::directory_iterator dir_iter(someDir) ; dir_iter != end_iter ; ++dir_iter)
{
if (fs::is_regular_file(dir_iter->status()) )
{
result_set.insert(result_set_t::value_type(fs::last_write_time(dir_iter->path()), *dir_iter));
}
}
}

You can then iterate through result_set, and the mapped boost::filesystem::path entries will be in ascending order.

How to sort files by time and also rename them?

here is one way to do so:

def rename(directory):
os.chdir(directory)
num = 1
for file in [file for file in sorted(os.listdir(), key=os.path.getctime) if os.path.splitext(file)[1] == ".txt"]:
if os.path.splitext(file)[1] == ".txt":
os.rename(file, f"name{num}.txt")
num += 1

We used sorted() to sort files by last modified date, using os.path.getctime()

To get the extension of the file, we used os.path.splitext().

Get files list in a folder order by Modified date desending

see this , may be it will help

//This is reusable method which takes folder path and returns sorted file list
-(NSArray*)getSortedFilesFromFolder: (NSString*)folderPath
{
NSError *error = nil;
NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.pdf'"];//Take only pdf file
filesArray = [filesArray filteredArrayUsingPredicate:predicate];

// sort by creation date
NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];

for(NSString* file in filesArray) {

if (![file isEqualToString:@".DS_Store"]) {
NSString* filePath = [folderPath stringByAppendingPathComponent:file];
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:filePath
error:&error];
NSDate* modDate = [properties objectForKey:NSFileModificationDate];

[filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
file, @"path",
modDate, @"lastModDate",
nil]];

}
}

// Sort using a block - order inverted as we want latest date first
NSArray* sortedFiles = [filesAndProperties sortedArrayUsingComparator:
^(id path1, id path2)
{
// compare
NSComparisonResult comp = [[path1 objectForKey:@"lastModDate"] compare:
[path2 objectForKey:@"lastModDate"]];
// invert ordering
if (comp == NSOrderedDescending) {
comp = NSOrderedAscending;
}
else if(comp == NSOrderedAscending){
comp = NSOrderedDescending;
}
return comp;
}];

return sortedFiles;

}

Python: Get a list of all files and folders in a directory, the time of creation, the time of last modification. System independent solution?

I know for a fact that os.stat functions well on both windows and linux.

Documentation here

However, to fit your functionality, you could do:

You can use st_atime to access most recent access and st_ctime for file creation time.

import os,time

def get_information(directory):
file_list = []
for i in os.listdir(directory):
a = os.stat(os.path.join(directory,i))
file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
return file_list

print get_information("/")

I'm on a mac and I get this,

[['.dbfseventsd', 'Thu Apr  4 18:39:35 2013', 'Thu Apr  4 18:39:35 2013'], ['.DocumentRevisions-V100', 'Wed May 15 00:00:00 2013', 'Sat Apr 13 18:11:00 2013'],....]


Related Topics



Leave a reply



Submit