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?
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