I wrote a program in Python that scans all files in a directory, makes dictionaries with stuff like date of creation and a hash of the contents of a file. Then i scan another directory which is just a copy of the original dir, but with some files added, deleted and changed. My program reports these changes.
import os
import stat
import hashlib
import json
class DirInfo:
def __init__(self):
self._dirInfo = {}
def probe(self, dirname):
fname = os.path.join(dirname, "data.txt")
blocksize = 512000000
for file in os.listdir(dirname):
if file != "data.txt":
fileWithPath = os.path.join(dirname, file)
fileInfo = {}
fileInfo['name'] = file
if os.path.isfile(fileWithPath):
sbuf = os.fstat(os.open(fileWithPath, os.O_RDONLY))
fileInfo['type'] = stat.S_IFMT(sbuf.st_mode)
fileInfo['mode'] = stat.S_IMODE(sbuf.st_mode)
fileInfo['mtime'] = sbuf.st_mtime
fileInfo['size'] = sbuf.st_size
hasher = hashlib.sha256()
with open(fileWithPath, 'rb') as x:
for chunk in iter(lambda: x.read(blocksize), b""):
hasher.update(chunk)
fileInfo['sha256'] = hasher.hexdigest()
if os.path.islink(fileWithPath):
fileInfo['symlink'] = os.readlink(fileWithPath)
self._dirInfo[file] = fileInfo
del fileInfo
DirInfo.save(self._dirInfo, fname)
pass
def compare(self, other):
pad = "D:\\Testmapje met random files\\data.txt"
pad2 = "D:\\Testmapje met random files 2\\data.txt"
dct = DirInfo.load(self, pad)
dct2 = DirInfo.load(other, pad2)
assert isinstance(other, DirInfo)
for key in dct:
if key not in dct2:
print (key, "is verwijderd")
for key in dct2:
fileHuidig = key
if key not in dct:
print (key, "is toegevoegd")
else:
allKeysPerFileMeasurement1 = (dct.get(key))
allKeysPerFileMeasurement2 = (dct2.get(key))
for key in allKeysPerFileMeasurement2:
Measurement1Value = (allKeysPerFileMeasurement1.get(key))
Measurement2Value = (allKeysPerFileMeasurement2.get(key))
if Measurement1Value != Measurement2Value:
print("In bestand:", fileHuidig, "was", key, Measurement1Value, "nu is", key, Measurement2Value)
return []
def save(self, fname):
json.dump(self, open(fname, 'w'))
pass
def load(self, fname):
return json.load(open(fname, 'r'))
if __name__ == '__main__':
dirname = "D:\\Testmapje met random files"
dirnameanders = "D:\\Testmapje met random files 2"
dirInfo1 = DirInfo()
dirInfo1.probe(dirname)
# change some files
dirInfo2 = DirInfo()
dirInfo2.probe(dirnameanders)
for err in dirInfo1.compare(dirInfo2):
print(err)
My program gives the following output:
LinkNaarTestFolder2 is verwijderd (deleted)
In bestand: Lief dagboek.txt was mtime 1530555920.17531 nu is mtime 1530723663.3718975
In bestand: Lief dagboek.txt was size 30 nu is size 22
In bestand: Lief dagboek.txt was sha256 c33b32ad0a34316c970febc149199ca59946e75753ddc6438f09d1204835d0e4 nu is sha256 4728379b3f491004319de08ca6161d0b47d3f7921d79d7a9b95e1ca2c458ed48
In bestand: LinkNaarTestFolder was symlink C:\Test voor python nu is symlink C:\Users\Kevin\Documents\Battlefield 3
lol.txt is toegevoegd (is added)
Any ways to make my code shorter?