'Python3 gnupg file encryption issue

I have a function to list all files in a directory and encrypt them with a public key. The issue I'm having is that if there are several files inside the directory some of them get corrupted. Like 2 or 3 of them would be a GPG file with exactly 858 bytes size and no content. If decrypt them I would have 0-byte size files.

Function

def gpg_encrypt(source):
  gpg = GPG(gnupghome='/home/mohs3n/.gnupg', use_agent=True)
  try:
    if os.path.isfile(source):
        if source.endswith('.gpg'):
          print(source + ' is already encrypted')
        else:
          stream = open(source, "rb")
          status = gpg.encrypt_file(stream, 'C05819CE8A9DA638BD6B6E08688D1CE89FCE05B3', armor=False, always_trust=True, output=source+'.gpg', symmetric=False)
          stream.close()
          if status.ok:
            os.remove(source)
            print(source, ' successfully encrypted')

    elif os.path.isdir(source):
      for root, dirs, files in os.walk(source, topdown=True):
        for name in files:
          current_file = (os.path.join(root, name))
          if current_file.endswith('.gpg'):
            print(current_file + ' : is already encrypted')
          else:
            stream = open(current_file, "rb")
            status = gpg.encrypt_file(stream, 'C05819CE8A9DA638BD6B6E08688D1CE89FCE05B3', armor=False, always_trust=True, output=source+'/'+name+'.gpg', symmetric=False)
            stream.close()
            if status.ok:
              os.remove(current_file)
              print(current_file + ' successfully encrypted')
                        
  except Exception as e:
    print(e)


Sources

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

Source: Stack Overflow

Solution Source