Re-arranging the naming convention of FITS file?

This script is for Python 3. Start it (py fixname.py) from the directory where the FIT files are located. It will rename only files were the sequence number is before the date and skip other files. I usually run it from the root of the sequences directory on an external SSD, where the calibrated frames are stored.

As always in such cases: the script comes with no warranty of any kind, use it at your own risk. I do :slight_smile:

Vitali

from os import listdir, rename
from os.path import isdir, isfile, join
from pathlib import Path
import re

def RenameFiles(Dir):
    # Read the list of files
    AllFiles = [f for f in listdir(Dir) if isfile(join(Dir, f))]
    ImageFiles = []
    for name in AllFiles:
        if '.xisf' in name or '.FIT' in name:
            ImageFiles.append(name)

    if len(ImageFiles) <= 0:
        return 0

    cRenamed = 0
    # Check all names
    for ImageFile in ImageFiles:
        # Check if the name contains "_001_20201106_035740_058_E"
        r = '_[0-9]{3}_[0-9]{8}_[0-9]{6}_[0-9]{3}_[E|W]'
        m = re.search(r, ImageFile)
        if m == None:
            #print("Skipped " + ImageFile)
            continue

        # Split the string to 4 parts: prefix, seqnum, date, suffix
        sPrefix = ImageFile[0:m.start()]
        sSeqNum = ImageFile[m.start():m.start()+4]
        sDate   = ImageFile[m.start()+4:m.end()-2]
        sSuffix = ImageFile[m.end()-2:]

        # Re-assemble, moving the seqnum after the date
        sNewName = sPrefix + sDate + sSeqNum + sSuffix

        sOldPath = join(Dir, ImageFile)
        sNewPath = join(Dir, sNewName)

        if isfile(sNewPath):
            #print("Skipped (target exists): " + ImageFile)
            continue

        #print(ImageFile)
        rename(sOldPath, sNewPath)
        cRenamed = cRenamed + 1

    return cRenamed


def ProcessDir(Dir):
    print('*** ' + Dir)
    cRenamed = RenameFiles(Dir)
    print(str(cRenamed) + ' files')

    AllDirs = [f for f in listdir(Dir) if isdir(join(Dir, f))]
    for Subdir in AllDirs:
        ProcessDir(join(Dir, Subdir))
    return

ProcessDir('.')