Search code examples
pythonpython-2.7python-os

identify a file with specific chars present in it and rename the file


I am trying to find and rename below files using below script

IYBR2C.YGPSWS.SL.1.M.20190503170641.csv to SAK_BB_AL.csv
QWEJ1P.YGPSWS.SL.1.M.20190508122932.csv to SAM_SG_MO.csv
SCPR1C.YGPSWS.SL.1.T.20190503164120.csv to SVM_SG_AL.csv
SMCE2P.SGPAWS.SL.1.T.20190508123138.csv to SDM_SG_MO.csv

This is what I have tried for a single file:

But my problem is I need to have some conditions on this renaming that is

ex-:
IYBR2C.YGPSWS.SL.1.M.20190503170641.csv to SAK_BB_AL.csv

for this example file I need to check whether it starts with "IYBR2C" and it contains "M" if this two conditions are met then rename it to SAK_BB_AL.csv

for root, dirs, files in os.walk(/tmp):
for dir in dirs:
    if dir.startswith("IYBR2C"):
        org_fp = os.path.join(root, dir)
        new_fp = os.path.join(root, dir[1])
        os.rename(org_fp, new_fp)

what I have tried gives no results as expected to find the file and rename it which starts with ("IYBR2C") and How can I check that it contains the letter ("M") as well.

Note : Files are present in my /tmp directory and I do not know how many of them are there I provided an example as to how I can achieve it for IYBR2C.YGPSWS.SL.1.M.20190503170641.csv , please provide a general solution :-)


Solution

  • This should get you going. you basically need two conditions in the if statement, checking first word and search for character in the name. Here is a mockup. Tell me if it is okay.

    filenames=['IYBR2C.YGPSWS.SL.1.M.20190503170641.csv',
    'QWEJ1P.YGPSWS.SL.1.M.20190508122932.csv',
    'SCPR1C.YGPSWS.SL.1.T.20190503164120.csv',
    'SMCE2P.SGPAWS.SL.1.T.20190508123138.csv']
    for newname in filenames:
             if(newname.split('.')[0]=='IYBR2C' and "M" in newname):
                    print newname,'SAK_BB_AL.csv'
    

    Result:

    IYBR2C.YGPSWS.SL.1.M.20190503170641.csv SAK_BB_AL.csv