(file_spec, vtype='copy')
| 1 | def VersionFile(file_spec, vtype='copy'): |
| 2 | import os, shutil |
| 3 | |
| 4 | ok = 0 |
| 5 | if os.path.isfile(file_spec): |
| 6 | # or do other error checking... |
| 7 | if vtype not in ('copy', 'rename'): |
| 8 | vtype = 'copy' |
| 9 | |
| 10 | # determine root file name so the extension doesn't get longer and longer... |
| 11 | n, e = os.path.splitext(file_spec) |
| 12 | |
| 13 | # is e an integer? |
| 14 | try: |
| 15 | num = int(e) |
| 16 | root = n |
| 17 | except ValueError: |
| 18 | root = file_spec |
| 19 | |
| 20 | # find next available file version |
| 21 | for i in xrange(1000): |
| 22 | new_file = '%s.%03d' % (root, i) |
| 23 | if not os.path.isfile(new_file): |
| 24 | if vtype == 'copy': |
| 25 | shutil.copy(file_spec, new_file) |
| 26 | else: |
| 27 | os.rename(file_spec, new_file) |
| 28 | ok = 1 |
| 29 | break |
| 30 | return ok |
| 31 | |
| 32 | if __name__ == '__main__': |
| 33 | # test code (you will need a file named test.txt) |
no test coverage detected