Directly write to encrypted file in Python
<p>In python, using the gnupg package, is it possible to take a value in memory, then write it an encrypted file rather than writing to file THEN encrypting?  </p>

<p>I was hoping something like this would work:</p>

<pre><code>import gnupg

gpg = gnupg.GPG(gnupghome='keydirectory')

l = [['a', '1'], ['b', '2'], ['c', '3']]

gpg.encrypt_file(l, recipients=['test@test.com'], output='encryptedfile.asc')
</code></pre>

<p>I was hoping there was a write concept like this to loop over line-by-line, but I can't find one.  </p>

<pre><code>with open('regularfile.txt', 'w') as file:
  for i in l:
    file.write(i)
</code></pre>

<p>Ideally, I could connect to a database and output a file by writing directly.  </p>

<p>The <a href="https://python-gnupg.readthedocs.io/en/latest/gnupg.html#gnupg.GPG.encrypt" rel="nofollow">documentation for the <code>GPG.encrypt</code> method</a> shows that is what you want.</p>

<pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; import gnupg

&gt;&gt;&gt; gpg = gnupg.GPG(homedir="doctests")
&gt;&gt;&gt; key_settings = gpg.gen_key_input(
...         key_type='RSA',
...         key_length=1024,
...         key_usage='ESCA',
...         passphrase='foo')
&gt;&gt;&gt; key = gpg.gen_key(key_settings)

&gt;&gt;&gt; message = "The crow flies at midnight."
&gt;&gt;&gt; encrypted = str(gpg.encrypt(message, key.printprint))
&gt;&gt;&gt; assert encrypted != message
&gt;&gt;&gt; assert not encrypted.isspace()

&gt;&gt;&gt; decrypted = str(gpg.decrypt(encrypted))
&gt;&gt;&gt; assert not decrypted.isspace()
&gt;&gt;&gt; decrypted
'The crow flies at midnight.'
</code></pre>

python gnupg