Writing shell scripts in Python

After browsing the web for some time, your download folder might be filled with a lot of files of different type. PDF files, image files and more. Or maybe you collected a lot of files in a temp folder and now you want to have a look at them by file type. Let’s say you work with Linux and have the following Bash script to clean up the mess.

CWD=”`pwd`/”

echo “Distributing files in $CWD :”

for e in $( ls ); do
   if [ `expr index “$e” .` -ne 0 ]
   then
      EXTDIR=”$CWD${e##*.}”
      if ! [ -e $EXTDIR ]
      then
         mkdir $EXTDIR
      fi
      echo “Moving $e to $EXTDIR …”
      mv “$CWD$e” $EXTDIR
   fi
done

echo “Done.”

This will move all files with an extension to a folder with the name of the extension. The output will look something like the following.

neifer@linux-asb4:~/tmp> ~/code/bash/distfiles.sh 
Distributing files in /home/neifer/tmp/ :
Moving fibonacci.py to /home/neifer/tmp/py …
Moving ListSample.java to /home/neifer/tmp/java …
Moving meWinter_.jpg to /home/neifer/tmp/jpg …
Moving slime.1.pdf to /home/neifer/tmp/pdf …
Moving svn-book.pdf to /home/neifer/tmp/pdf …
Done.

Now you wonder how this could be done in Python. The following script does the trick.

import os
import os.path
import shutil

cwd = os.getcwd() + os.sep

print “Distributing files in”, cwd, “:”

for e in os.listdir(cwd):
    if ‘.’ in e:
        extdir = cwd + os.path.splitext(e)[1][1:]
        if not os.path.exists(extdir):
            os.mkdir(extdir)
        print “Moving”, e, “to”, extdir, “…”
        shutil.move(cwd + e, extdir)


print “Done.”

As you can see, it is not that different. However, the Python version might be easier to read for the inexperienced user.
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s