Last active
December 12, 2015 08:59
-
-
Save davesque/4747981 to your computer and use it in GitHub Desktop.
Adjust file names based on time zone info
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| from dateutil import parser | |
| from dateutil.tz import gettz | |
| import csv | |
| import os | |
| import sys | |
| FORMAT = '%Y-%m-%d %H.%M.%SZ.pdf' | |
| UTC = gettz('UTC') | |
| class RenameError(Exception): | |
| pass | |
| def main(): | |
| if len(sys.argv) < 3: | |
| sys.stdout.write( | |
| """ | |
| Usage: {0} CSV_FILE FILES_DIR | |
| Renames PDF files based on data in a time zone correction csv file. | |
| """[1:].format(sys.argv[0]) | |
| ) | |
| sys.exit(0) | |
| csv_file = sys.argv[1] | |
| files_path = sys.argv[2].rstrip('/') | |
| with open(csv_file, 'r') as f: | |
| rs = list(csv.DictReader(f)) | |
| for line, r in enumerate(rs, 2): | |
| if not r['name'].endswith('Z.pdf'): | |
| raise RenameError('Error on line {line}: "{name}" does not end with "Z.pdf"!'.format( | |
| line=line, | |
| name=r['name'], | |
| )) | |
| date_string = (r['name'][:-5] + ' ' + r['zone']).replace('.', ':') | |
| try: | |
| date = parser.parse(date_string) | |
| except ValueError: | |
| sys.stderr.write('Error on line {0}: '.format(line)) | |
| raise | |
| date = date.astimezone(UTC) | |
| old_name = r['name'] | |
| old_path = '{files_path}/{old_name}'.format( | |
| files_path=files_path, | |
| old_name=old_name, | |
| ) | |
| new_name = date.strftime(FORMAT) | |
| new_path = '{files_path}/{new_name}'.format( | |
| files_path=files_path, | |
| new_name=new_name, | |
| ) | |
| os.rename(old_path, new_path) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment