Created
February 9, 2016 20:17
-
-
Save moonwatcher/256203b4748e818ff704 to your computer and use it in GitHub Desktop.
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 python3 | |
# -*- coding: utf-8 -*- | |
import json | |
import os | |
from subprocess import Popen, PIPE | |
inode_type = lambda path: ( os.path.isfile(path) and 'file' ) or 'directory' | |
def to_json(node): | |
return json.dumps(node, sort_keys=True, ensure_ascii=False, indent=4) | |
def collect(path, recursive, depth=1): | |
result = [] | |
if os.path.exists(path): | |
decoded = { | |
'path': path, | |
'inode type': inode_type(path), | |
'dirname': os.path.dirname(path), | |
'basename': os.path.basename(path), | |
'modified': False, | |
} | |
if decoded['inode type'] == 'file': | |
filename, decoded['extension'] = os.path.splitext(decoded['basename']) | |
if decoded['extension'] not in ['.avi', '.jpg', '.mov', '.tiff']: | |
decoded['extension'] = None | |
test(decoded) | |
result.append(decoded) | |
print(to_json(decoded)) | |
if decoded['inode type'] == 'directory' and (recursive or depth > 0): | |
for next in os.listdir(decoded['path']): | |
next = os.path.abspath(os.path.join(decoded['path'],next)) | |
result.extend(collect(next, recursive, depth - 1)) | |
return result | |
def scan(path): | |
inodes = [] | |
if os.path.exists(path): | |
path = os.path.abspath(os.path.expanduser(os.path.expandvars(path))) | |
inodes.extend(collect(path, True)) | |
return inodes | |
def test(decoded): | |
if decoded['inode type'] == 'file' and decoded['extension'] is None: | |
process = Popen(['file', decoded['path']], stdout=PIPE, stderr=PIPE) | |
output, error = process.communicate() | |
decoded['test'] = output.decode('utf8') | |
if 'TIFF' in decoded['test']: | |
decoded['extension'] = '.tiff' | |
decoded['modified'] = True | |
if 'QuickTime' in decoded['test'] or 'Infocom game data' in decoded['test']: | |
decoded['extension'] = '.mov' | |
decoded['modified'] = True | |
def rename(indoes): | |
for decoded in inodes: | |
if decoded['inode type'] == 'file' and decoded['modified']: | |
decoded['renamed path'] = decoded['path'] + decoded['extension'] | |
os.rename(decoded['path'], decoded['renamed path']) | |
print('renaming {} to {}'.format(decoded['path'], decoded['renamed path'])) | |
inodes = scan('.') | |
rename(inodes) | |
#print(to_json(scan('.'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment