Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a timestamp to a file name and move it

I have created the following python script that checks for the content of a source folder, copies all .txt files to destination folder, and moves all .csv files to destination folder.

This is the script-

import os
import shutil
from pathlib import Path
import time

source = "C:\\Users\\user\\Desktop\\source"
destination = "C:\\Users\\user\\Desktop\\destination"
date = time.strftime("%Y%m%d-%H%M%S")
files = os.listdir(source)

for file in files:
    if file.endswith('.txt'):
        shutil.copy2(os.path.join(source, file), destination)
    if file.endswith('.csv'):
        shutil.move(os.path.join(source, file), destination)

However, I would like it to add a timestamp to the file’s name before copying or moving it to the destination folder.
I have already defined date variable using time package but couldn’t get it right.
How can that be done?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance,

>Solution :

You could use os.path.splitext in order to separate your filename in (‘basename’, ‘extension’), and then insert your timestamp in the middle of it. Something like

import os

for file in files:
  basename, extension = os.path.splitext(file)

  
  destination_name = f"{basename}{date}{extension}"
  full_destination = os.path.join(destination, destination_name)
  if extension == '.txt':
  # etc etc

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading