[Tutor] gnupg within a for loop

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Sun Jun 1 18:22:30 CEST 2014


Adam Gold <awg1 <at> gmx.com> writes:

>  
> I start with the following which can be used to encrypt a single file
> (assume I have the indentations correct in the actual code, I can't seem
> to modify the wrapping with my email client):
> 
> phrase = '12345'
> cipher = 'AES256'
> gpg = gnupg.GPG(gnupghome='/home/adam/.gnupg')
> with open('/home/adam/file1', 'rb') as f:
>     status = gpg.encrypt_file(f, None, passphrase=phrase,
> symmetric=cipher.upper(), output='/home/adam/file1.gpg')
> 
> This produces a single encrypted file, 'file1.gpg'.  I then try to embed
> this in a for loop:
> 
> unencrypted = [u for u in os.listdir('/home/adam/temp')]
> for G in unencrypted:
>     gpg = gnupg.GPG(gnupghome='/home/adam/.gnupg')
>     phrase = '12345'
>     cipher = 'AES256'
>     with open (G, 'rb') as f:
> 		status = gpg.encrypt_file(f, None, passphrase=phrase,
> symmetric=cipher.upper(), output=G + '.gpg')
> 
> This produces the following error:
> Traceback (most recent call last):
>   File "<pyshell#8>", line 5, in <module>
>     with open (G, 'rb') as f:
> FileNotFoundError: [Errno 2] No such file or directory: 'file1'
> 
> It seems 'G', which I'm intending to represent each successive element
> of the list as the for loop iterates, does not find its way into the
> gnupg code lines.  I have a feeling I'm missing something really basic
> here :)

The really basic thing is that os.listdir returns the file names it finds in
the specified directory, but that does not include the path to the file
again. So the first element of unencrypted in your case is just 'file1' and
that doesn't seem to exist in your working directory. You'll have to prepend
your original path '/home/adam/temp/' to it again (via os.path.join for
example).

Best,
Wolfgang






More information about the Tutor mailing list