0

I'm trying to unzip a file, and read one of the extracted files, and delete the extracted files.

  1. Files extracted (e.g. we got file1 and file2)
  2. Read file1, and close it.

    with open(file1, 'r') as f:
        data = f.readline()
    f.close()
    
  3. Do something with the "data".

  4. Remove the files extracted.

    os.remove(file1)
    

Everything went fine, except it received these messages at the end. The files were also removed. How do I close the files properly?

    /tmp/file1: No such file or directory
    140347508795048:error:02001002:system library:fopen:No such file or directory:bss_file.c:398:fopen('/tmp/file1','r')
    140347508795048:error:20074002:BIO routines:FILE_CTRL:system lib:bss_file.c:400:

UPDATE: (My script looks similar to these)

#!/usr/bin/python
import subprocess, os

infile = "filename.enc"
outfile = "filename.dec"
opensslCmd = "openssl enc -a -d -aes-256-cbc -in %s -out %s" % (infile, outfile)   
subprocess.Popen(opensslCmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,      close_fds=True)
os.remove(infile)

2 Answers 2

3

No need to close a file handle when using with with a file context manager, the handle is automatically closed when the scope have changed, i.e. when readline is done.

See python tutorial

4
  • Then why is it showing the file errors the script? I removed the f.close(), it didn't help. Commented Jun 1, 2011 at 9:53
  • I think you need to add some more code above to show what is the cause of this, hard to tell from your snippet Commented Jun 1, 2011 at 10:21
  • I found what is causing this: subprocess.Popen(mycommand, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True). The command is just an openssl command that input one of the files that I extracted. How do I do it properly? I'm sorry for these newbie questions. Commented Jun 2, 2011 at 6:12
  • @superNobody post a new question, don't forget to post all of your code. This Q is accepted; hence people might skip reading it... Commented Jun 2, 2011 at 7:53
2

The errors you see are not errors as Python would report them. They mean something other than Python tried to open these files, although it's hard to tell what from your little snippet.

If you're simply trying to retrieve some data from a zip file, there isn't really a reason to extract them to disk. You can simply read the data directly from the zip file, extracting to memory only, with zipfile.ZipFile.open.

1
  • I wasn't aware of that. It's good to know. The process involves taking one of the extracted files as input into "openssl" command and execute through subprocess. subprocess.Popen(mycommand, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True). That is what's causing the error. I'm still looking for a workaround. Commented Jun 2, 2011 at 6:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.