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.

Erica
  • 8,974
  • 4
  • 34
  • 79
Ed Hawkins
  • 189
  • 1
  • 2
  • 8
  • 1
    You'll also have to replace the space with an underscore. – nmpeterson Sep 16 '14 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 Sep 16 '14 at 17:59

1 Answers1

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

plablo09
  • 513
  • 3
  • 10
  • That works great thanks! I was using ArcPy 2.7 I apologize if I used the wrong forum. – Ed Hawkins Sep 16 '14 at 18:00
  • my workspace is C:\Project\out. in the right code there no mention to where to execute it. – newGIS Apr 21 '15 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 Apr 21 '15 at 18:03
  • How would you make it so that the files are copied from one director to another leaving the originals intact? – Anthony Stokes Oct 04 '16 at 04: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 Oct 05 '16 at 22:33