munyal-client/dir_to_json.py

53 lines
1.5 KiB
Python
Raw Normal View History

2019-07-28 16:18:49 +00:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
2019-11-27 23:24:04 +00:00
import os
from hashlib import md5
2019-07-28 16:18:49 +00:00
def md5sum(filename):
try:
hash = md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(128 * hash.block_size), b""):
hash.update(chunk)
return hash.hexdigest()
2019-11-27 23:24:04 +00:00
except Exception:
2019-07-28 16:18:49 +00:00
return None
2019-11-27 23:24:04 +00:00
2019-07-28 16:18:49 +00:00
def get_json(path):
out = []
items = os.listdir(path)
try:
for item in items:
if item[0] != ".":
2019-11-27 23:24:04 +00:00
item_json = {"name": item}
2019-07-28 16:18:49 +00:00
route = os.path.join(path, item)
if os.path.isdir(route):
item_json["is_file"] = False
item_json["content"] = get_json(route)
elif os.path.isfile(route):
item_json["is_file"] = True
item_json["size"] = os.path.getsize(route)
item_json["last_modified"] = os.path.getmtime(route)
item_json["created_at"] = os.path.getctime(route)
checksum = md5sum(route)
if checksum:
item_json["checksum"] = checksum
else:
item = None
2019-11-27 23:24:04 +00:00
else:
continue
2019-07-28 16:18:49 +00:00
out.append(item_json)
2019-11-27 23:24:04 +00:00
except Exception:
2019-07-28 16:18:49 +00:00
return get_json(path)
return out
2019-11-27 23:24:04 +00:00
2019-07-28 16:18:49 +00:00
if __name__ == "__main__":
2019-11-27 23:24:04 +00:00
output = get_json(
"/media/kirbylife/DATOS/Proyectos/PyCharmProjects/Munyal/folder_test")
2019-07-28 16:18:49 +00:00
print(json.dumps(output, indent=4))