Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
shutil.copy questions
#1
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.
Reply
#2
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)
Reply
#3
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?
Reply
#4
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('.'))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 228 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  use of shutil.copytree with ENOTDIR exception yan 2 882 Nov-29-2023, 03:02 PM
Last Post: yan
  shutil.move make data corrupt kucingkembar 0 785 Feb-01-2023, 01:30 PM
Last Post: kucingkembar
  Merge htm files with shutil library (TypeError: 'module' object is not callable) Melcu54 5 1,572 Aug-28-2022, 07:11 AM
Last Post: Melcu54
  extra slashes in the network path for shutil.copy tester_V 3 3,749 Jun-02-2021, 07:57 AM
Last Post: supuflounder
  concatenat - shutil jmabrito 3 2,164 Feb-11-2021, 12:17 PM
Last Post: jmabrito
  Shutil FileNotFoundError: Errno 2 Help lord_kaiser 8 10,480 Aug-10-2020, 08:45 AM
Last Post: lord_kaiser
  Shutil move if file exists in destination Friend 2 6,740 Feb-02-2020, 01:45 PM
Last Post: Friend
  Shutil attempts to copy directories that don't exist ConsoleGeek 5 4,512 Oct-29-2019, 09:26 PM
Last Post: Gribouillis
  Help copying files with shutil hikerguy62 2 4,266 Aug-02-2019, 08:16 PM
Last Post: hikerguy62

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020