Tuesday, September 1, 2009

Truncate file extension using python glob


My current directory contains the following 2 files.

$ ls -1
20061117.dat.dat
details.dat.dat.dat

Required: Move(rename) the above files to single .dat extension (e.g. details.dat.dat.dat to details.dat)
The python code using glob module:

>>> import os,glob
>>> for file in glob.glob("*.dat"):
... newF=".".join(file.split(".")[:2])
... os.rename(file,newF)
...

Now:

$ ls -1
20061117.dat
details.dat


Using glob module we can use wildcards with Python according to the rules used by the Unix shell. More about it can be found here

Few more examples:

# lists all files in the current directory
glob.glob('*')

# returns all .dat extension files
glob.glob('*.dat')

# lists all files starting with a letter, followed by 3 characters (numbers, letters) and any ending.
glob.glob('[a-z]???.*')

1 Comment:

JustGlowing said...

Glob is a good tools. When you have a lot of file to process it make you able to filter a lot of them without comparing their names.