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.
echo “Distributing files in $CWD :”
for e in $( ls ); do
if [ `expr index “$e” .` -ne 0 ]
if ! [ -e $EXTDIR ]
echo “Moving $e to $EXTDIR …”
mv “$CWD$e” $EXTDIR
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.
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 …
Now you wonder how this could be done in Python. The following script does the trick.
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:]
if not os.path.exists(extdir):
print “Moving”, e, “to”, extdir, “…”
shutil.move(cwd + e, extdir)