A while back when still fairly new to Python, this simple program was developed to back directories of information. In reality, it is just a simple (and poorly written) file copier that could be greatly improved. This is committed for archival to be run under Python 2.5 or later versions.
Python, 36 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
import os import sys def main(): try: source, destination = sys.argv[1:] assert os.path.isdir(source), '<source_directory> is not a directory' if os.path.exists(destination): assert os.path.isdir(destination), \ '<destination_directory> is not a directory' else: os.makedirs(destination) copy(source, destination) except Exception, error: program = 'USAGE: %s <source_directory> <destination_directory>' % \ os.path.basename(sys.argv) problem = 'ERROR: %s' % error divider = '=' * max(len(program), len(problem)) sys.stdout.write('\n%s\n%s\n%s\n' % (program, divider, problem)) def copy(source, destination): for name in os.listdir(source): source_name = os.path.join(source, name) destination_name = os.path.join(destination, name) try: if os.path.isdir(source_name): os.mkdir(destination_name) copy(source_name, destination_name) elif os.path.isfile(source_name): file(destination_name, 'wb').write( file(source_name, 'rb').read()) except: sys.stderr.write('\n%s\n%s\n' % (source_name, destination_name)) if __name__ == '__main__': main()
I don't understand the purpose of posting a recipe that is "poorly written". And I also don't understand what "committed for archival" is meant to convey. To this newbie, it appears that the practical impact is just more litter for the commons.
Please. What is your intent in posting a recipe like this?
Good question! I have several reasons of debatable quality:
@Stephan, I agree with Dan. To get the feedback you seem to want as well as show newbies what to (or not to) do, I suggest you post things like this on stackoverflow.com instead.
Thank you! I already have an account there ( http://stackoverflow.com/users/216356/noctis-skytower ) and have been an active member for quite a while already. Plenty of experience for getting feedback from stackoverflow.com has already been acquired. This recipe is not for me to get feedback but to act as a beginner's demonstration to others.
Sigh...the world doesn't need another source of examples of poorly written code -- nor do beginners.