Created
February 12, 2013 03:38
-
-
Save davesque/4760070 to your computer and use it in GitHub Desktop.
Rename files based on timestamp 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 files based on timestamps in a csv file. Files are renamed to the | |
equivalent UTC value of the timestamp. | |
Example csv content: | |
name,time | |
2007 partitionA_Part1.pdf,2007-09-12 20.29.20 -0400 | |
2007 partitionA_Part2.pdf,2007-08-17 13.37.07 -0400 | |
2007 partitionA_Part4.pdf,2007-04-11 10.08.49 -0400 | |
2007 partitionA_Part5.pdf,2007-03-28 23.33.36 +0000 | |
... | |
"""[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): | |
try: | |
date = parser.parse(r['time'].replace('.', ':')) | |
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, | |
) | |
try: | |
os.rename(old_path, new_path) | |
except OSError as e: | |
if e.errno == 2: | |
sys.stderr.write('Error on line {line}: file "{old_path}" not found!\n'.format( | |
line=line, | |
old_path=old_path, | |
)) | |
else: | |
raise | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment