Saturday, July 4, 2009

Move files based on condition in python


Contents of /tmp/mydir/

$ ls /tmp/mydir/ | paste -

logWA241.dat
logWA249.dat
logWA258.dat
logWA259.dat

Required: Move the above files to directories under /tmp/mydir such that logWA241.dat should go to dir /tmp/mydir/1, similarly logWA258.dat to /tmp/mydir/8 (i.e. dir name with last digit before .dat extn)

The python script:

import os
DIR="/tmp/mydir"
for file in os.listdir(DIR):
Absfile = os.path.join(DIR,file)
if os.path.isfile(Absfile) and file.endswith(".dat"):
Dname = Absfile.split(".")[:-1][-1][-1:]
Dname = os.path.join(DIR,Dname)
if not os.path.exists(Dname):
os.mkdir(Dname)
os.system('mv '+Absfile+' '+Dname)
else:
os.system('mv '+Absfile+' '+Dname)


The contents of /tmp/mydir/ after exection of the above script.

$ ls -R /tmp/mydir/

o/p:

/tmp/mydir/:
1 8 9

/tmp/mydir/1:
logWA241.dat

/tmp/mydir/8:
logWA258.dat

/tmp/mydir/9:
logWA249.dat logWA259.dat

Related concepts and modules:
- Python os module

0 Comments: