Python Forum
shutil.copy questions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: shutil.copy questions (/thread-28316.html)



shutil.copy questions - kristianpython - Jul-14-2020

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.


RE: shutil.copy questions - Gribouillis - Jul-14-2020

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)



RE: shutil.copy questions - kristianpython - Jul-14-2020

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?


RE: shutil.copy questions - Gribouillis - Jul-14-2020

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