Replace file names in a folder

06-25-2019 04:00 PM
Occasional Contributor
import arcpy
import os

arcpy.env.workspace = r"C:\Users\natb0\OneDrive -\GIS\GIS\Data\Dry_Creek\TerrAvion_Imagery\062319"
input_folder = arcpy.env.workspace

for p in os.listdir(input_folder):
    p.replace("CIR_4326", "RGB_062319")
    p.replace("TIRS_T_4326", "Temp_062319")
    p.replace("NDVI_NDVI_2_4326", "NDVI_062319")
    print p‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

I have to download 48 images from a website weekly, and I would like to write a script to rename the files to something more user friendly and understandable.  For each farm field (16 fields total), I download 3 images (#farmfield_TIRS_T_4326.tiff, #farmfield_CIR_4326.tiff, and #farmfield_NDVI_NDVI_2_4326.tiff), where TIRS = temperature, CIR = infrared, and NDVI is NDVI. For each file name, I would like to replace "TIRS_T_4326" with "Temp_062319",  "CIR_4326" with "RGB_062319", and "NDVI_NDVI_2_4326" with "NDVI_062319".  When I run the code, it runs fine but the file names do not change.  So Im guessing .replace is the wrong argument.  Does anyone know what I should use instead? My goal is to do a find a replace on the file names. 

0 Kudos
3 Replies
MVP Esteemed Contributor



so we can comment with line numbers.

Could you provide information beyond 'but I know it is wrong'  Does it now do what you want? are there errors?

Sample of errors or print statements.

Also, OneDrive and other non-local drives can be sketchy and folders that begin with numbers can be an issue as well.

0 Kudos
Occasional Contributor

Thanks for your input as always.  I updated my question per your recommendations. 

0 Kudos
MVP Esteemed Contributor

Natalie, you are going to have to add the path even though you set the workspace (which only Arc* cares about)

For example

for f in os.listdir(input_folder):
    if 'arr' in f:
        old = "{}\\{}".format(input_folder, f)
        os.rename(old, old.replace('arr', 'arrnew'))

Try a few files in C:\temp!, your paths are still .... (see my recently edited blog  /blogs/dan_patterson/2016/08/14/filenames-and-file-paths-in-python  and check your flotsam)

It renamed a bunch of text files that contained 'arr' in them

Line 3 is the workspace folder (like you did), it just safely appends the existing filename 'f' to the path to create 'old'

Then os.rename takes 'old' and replaced 'arr' with 'arrnew'

Hope you get the drift I hope

0 Kudos