Python – file name adjustments

Question:

I have a number of csv files (6) in a Linux folder that I need to rename and relocate to a new folder on the same server.

<entity_name>_yyyymmdd_hhmmss.csv – bearing in mind the <entity_name> is a string that varies from file to file.

I need to be able to keep the original <entity_name> but replace the yyyymmdd_hhmmss with to day’s date in the format yyyymmdd, so what we end up with is <entity_name>_yyyymmdd.csv

if this could be done using Python thanks.

Being new to Python the Internet was awash with ideas, some were close, but none seemed to help me achieve what I am after.

I have successfully manged to loop through the folder I need and read each file name, but am stuck renaming the files.

Asked By: Jag

||

Answers:

It’s just straight-line coding. For each file, extract the base, add the date and extension, and rename.

import os
import glob
import datetime

today = datetime.date.today().strftime('%Y%m%d')
newpath = "wherever/we/go/"
for name in glob.glob('*.csv'):
    base = name.split('_',1)[0]
    newname = f'{base}_{today}.csv'
    os.rename( name, newpath+newname )
Answered By: Tim Roberts
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.