Python Forum

Full Version: shutil.copy questions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I want to run a script that uses the shutil module to copy the last added file. I can use the code below to copy a file, but how would I go about telling it to copy the last modified file only instead of naming the file. Every 20th file would also work. This is to make it easier when creating timelapses for construction with the intent to host the script on a server that runs once a day.

import shutil

shutil.copy("file.txt", "backup")

break
Any help would be appreciated.
You can select the last modified file in the directory
from pathlib import Path

def last_modified(direc):
    """Return the most recently modified file in a directory

       The file is returned as a Path instance.
       Raise ValueError if there is no such file."""
    return max((p for p in Path(direc).iterdir() if p.is_file()),
                key=lambda p: p.stat().st_mtime)
I've tried below

import shutil
import pathlib
from pathlib import Path


def last_modified(direc):
    return max((p for p in Path(direc).iterdir() if p.is_file()),
                key=lambda p: p.stat().st_mtime)

source = 'last_modified(direc)'
target = 'backup'

shutil.copy(source, target)

print('complete')
Any ideas on how to get the def last_modified(direc): selected by shutil.copy?
Do you speak python? You need to call the function with the directory that you want as argument. For the current directory, you can normally pass '.' or Path.cwd()
source = str(last_modified('.'))