'f.read() doesn't read nothing in the 2nd iteration of a loop

I am trying to create a script that reads files from a directory and create a .txt file that maps the name of the file with its hash code (SHA256).

These are the imports and global variable declarations:

import os
from unicodedata import name
import hashlib

hashsha = hashlib.sha256()
directorio_config = r"C:\Users\santi\Documents\wsp_py\PA1\config"
directorio = r"C:\Users\santi\Documents\wsp_py\PA1\ficheros"
aux = dict()
BUF_SIZE = 65536  # lets read stuff in 64kb chunks!

I have two functions:

def get_ficheros(directorio, directorio_config):
    with os.scandir(directorio) as ficheros:
        for elemento in ficheros:
            if elemento.is_file():
                nombre_fichero = elemento.name
                ruta = directorio + "\\" + nombre_fichero
                hash_code = hash_file(ruta)
                aux[elemento.name] = hash_code
            else:
                newdir = directorio + "\\" + elemento.name
                get_ficheros(newdir, directorio_config)
        return aux

This one is suposed to read the files from a directory and put them in a dictionary where the value is the hash calculated by the hash_file function. Here it is:

def hash_file(filename):
    with open(filename, 'rb') as f:
        while True:
            data = f.read(BUF_SIZE)
            if not data:
                break
            hashsha.update(data)
        f.close()    

return hashsha.hexdigest()

This code works properly untill the first iteration. In the second iteration, f.read() reads b'' and it is stored in the variable "data" instead the second file hash code as it is expected. I have no idea why this happens. Any help is appriciated. Thnks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source