Python fácil de organizar

Explicação

Aqui está um código simples que escrevi anos atrás para organizar facilmente vários arquivos em subdiretórios de acordo com seus nomes (usando expressões regulares). Desculpe pelos erros que eu poderia ter cometido … Espero que seja útil.

Código

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Created by por Noelia Sales Montes

# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or any later version.

# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.

# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.

# Contact:
# noelia.salesmontes@gmail.com

"""
Python script that organizes the working directory files according to their

name.


CORRECT USAGE: python organize.py [-v] [-h|-s|-f]

* -v -> enable verbose mode

* -h o --help

* -s o --secure -> copy files

* -f o --force -> force the movement of files

If file already exists, it is deleted

"""


import sys
import os
import shutil
import getopt
import glob

# Regular expressions of files to process
__exreg__
= ['*.mp3', '*.hs', '*.py']
# Directories for each of the above files
__dirs__
= ['/home/nessa/Music', '/home/nessa/Haskell', '/home/nessa/Python']
# Options
__verbose__
= False
__secure__
= False
__force__
= False

def usage():
"""
Print usage

"""

print "USAGE: python organize.py [-v] [-h|-s|-f]"

def organize():
"""
Main function which classifies files according to the regular expressions

"""

indice
= 0
for exp in __exreg__:
if __verbose__ == True:
print "Regular expression: %s" % exp

# Find files that match with the regular expression
for __f in glob.glob(exp):
move
(__f, indice)
indice
+= 1


def move(__f, __ind):
"""
Files movement

"""

# Ensures the directory exists
if not os.path.exists(__dirs__[__ind]):
if __verbose__ == True:
print "Creating %s" % __dirs__[__ind]
os
.makedirs(__dirs__[__ind])

if __verbose__ == True:
print "%s => %s" % (__f, __dirs__[__ind])

# Copy (__secure__ mode) or move
try:
if __secure__ == True:
shutil
.copy(__f, __dirs__[__ind])
else:
shutil
.move(__f, __dirs__[__ind])
except shutil.Error:
# If there is any problem, move is forced
if __force__ == True:
try:
os
.remove(os.path.join(__dirs__[__ind], __f))
print os.path.join(__dirs__[__ind], __f)
if __secure__ == True:
shutil
.copy(__f, __dirs__[__ind])
else:
shutil
.move(__f, __dirs__[__ind])
except shutil.Error:
print "%s wasn't moved" % __f
else:
print "%s wasn't moved'" % __f


if __name__ == "__main__":
try:
__opts__
, __args__ = getopt.getopt(sys.argv[1:],
'shvf', ["secure", "help",
"__force__"])
except getopt.GetoptError, __err:
# Print error and help
print str(__err)
usage
()
sys
.exit(2)

# Identify options
for o, a in __opts__:
if o == "-v":
__verbose__
= True
elif o in ("-h", "--help"):
usage
()
sys
.exit()
elif o in ("-s", "--secure"):
__secure__
= True
elif o in ("-f", "--__force__"):
__force__
= True
else:
assert False, "Unsupported option"

organize
()