0

I need to copy the newest version of a file from A directory to B directory.

The files are generated monthly and are called "20220101 File.txt" "20220201 File.txt" "20220301 File.txt" and so on.

How can I copy every month the "latest" version of the file? For example, on August, the file "20220801 File.txt" should be copied to B directory.

I have copied it "manually" using Robocopy, but I don't know how to do it automatically.

It doesn't matter if Python is used or any other tool.

Aragorn64
  • 149
  • 7
  • 1
    You might want to share some code, either python or powershell to have better chances at someone helping you instead of expecting to have it coded for you – Santiago Squarzon Sep 01 '22 at 18:10

3 Answers3

1

assuming it is not a directory containing a huge number of files this should do what you want:

$destinationPath = "C:\folderA"
$sourcePath =  "C:\folderB"
$newestFile = (get-childitem $sourcePath | Sort-Object -Property CreationTime -Descending)[0]

copy-item -Path $newestFile.pspath -Destination $destinationPath -force

It does not recognize the date information in the filename, it uses the creationDate of the file to identify the newest one.

Toni
  • 1,738
  • 1
  • 3
  • 11
1

In this case, you can easily do it with Python.

from datetime import datetime
import shutil
    
month = str(datetime.today().strftime('%Y%m'))+ "01 File.txt" #it will be 20220901 File.txt
src_path = f"C:\A\{month}"
dst_path = f"C:\B\{month}"
shutil.copyfile(src_path, dst_path) #I copy the file from directory A and paste it on directory B , the destination file will have the same name of the original file. 
Bored Nerd
  • 64
  • 3
0

Totally agree with @Santiago, didn't provide any attempt to solve the problem.

That being said, with a few libraries this is possible to do easily. Mainly combination of finding all the files in A directory (using glob), and copying the file in the new directory (using shutil).

import shutil
from glob import glob
from datetime import date

location_1 = "in"
location_2 = "out"

files_to_copy = glob(f"{location_1}/*.txt")
files_to_copy.sort() # think glob already gives in sorted order, but added just in case

file_to_copy = files_to_copy[-1]
name = file_to_copy.split("/")[-1]
shutil.copy(file_to_copy, f"{location_2}/{name}")

if you want to add information about date or you replace the last line with:

shutil.copy(file_to_copy, f"{location_2}/{date.today().strftime('%d_%m_%Y')}_{name}")

For reference look up stackoverflow about moving files and how to get current time in python besides the documentation from the libraries already mentioned.

Warkaz
  • 845
  • 6
  • 18