Home > Back-end >  Python - file name adjustments
Python - file name adjustments

Time:12-20

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.

CodePudding user response:

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 )
  • Related