[Tutor] gnupg within a for loop

Jim Byrnes jf_byrnes at comcast.net
Sun Jun 1 18:53:12 CEST 2014


On 06/01/2014 07:01 AM, Adam Gold wrote:
> Hi there.  I'm trying to do the following using python 3: create a list
> from all files in a particular directory, then loop over that list
> symmetrically encrypting each file using the gnupg module (note, for the
> moment I'm embedding the passphrase in the code while obviously in
> practice it would have to be inputted by the user).
>
> 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')

Here you are giving with open( ) a full path to file1

>
> 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')]

If I run this code with my info and print it, I get a list of files in 
my temp directory.

> 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')

If I then do:

for G in unencrypted:
     print(G)

I get just a file name printed on each line.

When you do:

with open (G, 'rb') as f:

I think you have lost the path info for the files. If you give with 
open() path info it should work.  Hopefully if I am wrong someone with 
more knowledge will step in and give you a better answer.

Regards,  Jim

>
> 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 :)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>




More information about the Tutor mailing list