4

I am converting a directory of kml files to 1 single fGDB, but they all have the date as the file name. This creates a problem when using the original name because of the number at the beginning of the file name, it also has hyphens in the name of the file i.e. 2011-09-16 123.kml

I need to use python to change the - to _ and add KML to the beginning of every file in the directory.

2
  • 1
    You'll also have to replace the space with an underscore.
    – nmpeterson
    Commented Sep 16, 2014 at 17:58
  • 1
    I believe you will also need to change the spaces to something else (either remove them entirely, or change to underscores). It should be straightforward to do in the same manner as the hyphens -- see plablo09's script below.
    – Erica
    Commented Sep 16, 2014 at 17:59

1 Answer 1

4

Well, this is not strictly a GIS question, but since you asked and I just did something very similar, here it goes:

import glob
import os

for f in glob.glob('*.kml'):
    new_filename = f.replace("-","_")
    new_filename = "kml_" + new_filename
    os.rename(f,new_filename)

Haven't tested it but it should work

5
  • That works great thanks! I was using ArcPy 2.7 I apologize if I used the wrong forum.
    – Ed Hawkins
    Commented Sep 16, 2014 at 18:00
  • my workspace is C:\Project\out. in the right code there no mention to where to execute it.
    – newGIS
    Commented Apr 21, 2015 at 10:16
  • @newGIS you must execute the code from within the directory containing the files you want to rename. Or alternatively, you could specify a full path in glob.glob
    – plablo09
    Commented Apr 21, 2015 at 18:03
  • How would you make it so that the files are copied from one director to another leaving the originals intact? Commented Oct 4, 2016 at 4:57
  • @AnthonyStokes for that you could use something like copyfile. You just get the new filename and pass it (together with the new path) to copyfile
    – plablo09
    Commented Oct 5, 2016 at 22:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.