How to recursively find the latest modified file in a directory?
find . -type f -printf '%T@ %p\n' \
| sort -n | tail -1 | cut -f2- -d" "
For a huge tree, it might be hard for sort
to keep everything in memory.
%T@
gives you the modification time like a unix timestamp, sort -n
sorts numerically, tail -1
takes the last line (highest timestamp), cut -f2 -d" "
cuts away the first field (the timestamp) from the output.
Edit: Just as -printf
is probably GNU-only, ajreals usage of stat -c
is too. Although it is possible to do the same on BSD, the options for formatting is different (-f "%m %N"
it would seem)
And I missed the part of plural; if you want more then the latest file, just bump up the tail argument.
How can I list (ls) the 5 last modified files in a directory?
Try using head or tail. If you want the 5 most-recently modified files:
ls -1t | head -5
The -1 (that's a one) says one file per line and the head says take the first 5 entries.
If you want the last 5 try
ls -1t | tail -5
How to get last modified file in a directory?
You can do basically this:
- get the list of files
- get the time for each of them (also check
os.path.getmtime()
for updates) - use
datetime
module to get a value to compare against (that 1h) - compare
For that I've used a dictionary to both store paths and timestamps in a compact format. Then you can sort the dictionary by its values (dict.values()
) (which is a float, timestamp) and by that you will get the latest files created within 1 hour that are sorted. (e.g. by sorted(...)
function):
import os
import glob
from datetime import datetime, timedelta
hour_files = {
key: val for key, val in {
path: os.path.getctime(path)
for path in glob.glob("./*")
}.items()
if datetime.fromtimestamp(val) >= datetime.now() - timedelta(hours=1)
}
Alternatively, without the comprehension:
files = glob.glob("./*")
times = {}
for path in files:
times[path] = os.path.getctime(path)
hour_files = {}
for key, val in times.items():
if datetime.fromtimestamp(val) < datetime.now() - timedelta(hours=1):
continue
hour_files[key] = val
Or, perhaps your folder is just a mess and you have too many files. In that case, approach it incrementally:
hour_files = {}
for file in glob.glob("./*"):
timestamp = os.path.getctime(file)
if datetime.fromtimestamp(timestamp) < datetime.now() - timedelta(hours=1):
continue
hour_files[file] = timestamp
Get most recent file in a directory on Linux
ls -Art | tail -n 1
This will return the latest modified file or directory. Not very elegant, but it works.
Used flags:
-A
list all files except .
and ..
-r
reverse order while sorting
-t
sort by time, newest first
How do I find the last modified file in a directory in Java?
private File getLatestFilefromDir(String dirPath){
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}
How do I pull the 'last modified time' of each file within a directory in Python?
The os.listdir()
method lists the files of the given path excluding the path, hence you will need to concatenate the path yourself:
for file in os.listdir('../File Transfer/Old Files/'):
if file.endswith('.txt'):
time_mod = os.path.getmtime('../File Transfer/Old Files/' + file)
print(time_mod)
The glob.glob()
method works great in cases like this:
import os
import glob
for file in glob.globr('../File Transfer/Old Files/*.txt'):
time_mod = os.path.getmtime('../File Transfer/Old Files/' + file)
print(time_mod)
You can get the amount of hours passed since the last modification of each file like so:
import os
from time import time
PATH = '../File Transfer/Old Files/'
for file in os.listdir(PATH):
if file.endswith('.txt'):
time_mod = time() - os.path.getmtime(PATH + file)
print(time_mod // 3600)
How to get the latest file in a folder?
Whatever is assigned to the files
variable is incorrect. Use the following code.
import glob
import os
list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
Getting last modified for every file in a directory
The path
argument to os.stat
must be a string but you are passing in an instance of Path
. You need to convert Path
to string using str
.
for file in asm_pths:
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(str(file))
print("last modified: %s" % time.ctime(mtime))
But if you only want last modification date then os.path.getmtime
will be fine:
for file in asm_pths:
print("last modified: %s" % time.ctime(os.path.getmtime(str(file)))
Related Topics
Setting a PHP Script as a Windows Service
Run a PHP Script Every Second Using Cli
Php: Split String into Array, Like Explode with No Delimiter
Wampserver PHPmyadmin Maximum Execution Time of 360 Seconds Exceeded
How to Add Square Braces Around Subarray Data Inside of a JSON Encoded String
A Recursive Remove Directory Function for PHP
Create Image from Url Any File Type
Make Switch Use === Comparison Not == Comparison in PHP
How to Redirect to Another Page Using PHP
Getting Static Property from a Class with Dynamic Class Name in PHP
How to Customize Fos Userbundle Urls
How to Populate HTML Dropdown List with Values from Database
Downloading Attachments to Directory with Imap in PHP, Randomly Works
Is PHP's 'Include' a Function or a Statement
Combine PHP Prepared Statments with Like
PHP How to Write Data to Middle of File Without Rewriting File