Samuel García
Samuel García

Reputation: 2225

Can't read from NamedTemporaryFile after being written

I'm trying to download a file to a temp file and posting this file to another service. I tried this using NamedTemporaryFile but i'm being forced to close the file and reopen it.

def main():
    validate()
    logging.basicConfig(filename=sys.argv[2]+".log", level=logging.INFO)

    if(sys.argv[3][0:4] == "http"):
        filename = None
        with tempfile.NamedTemporaryFile("w+b", delete=False) as file:
            download(file, sys.argv[3])
            #this logging prints nothing
            logging.debug(file.readlines())
    else:
        #this else just process a local file...


def download(file, url):
    logging.info("Downloading file " + sys.argv[3] + "...")
    start = time.time() * 1000
    r = requests.get(sys.argv[3], stream=True, timeout=2.0)

    #just a dummy check....
    if r.status_code == 200:
        for chunk in r.iter_content():
            file.write(chunk)

        file.flush()
    else:
        logging.error("Server returned an error")
        raise StandardError

If I reopen the file outside the with block and I tried to read it, it just works. I don't understand why I have to close the temporary file and reopen it.

Can someone give me an explanation about this. I'm pretty new in python dev.

Upvotes: 2

Views: 618

Answers (1)

krase
krase

Reputation: 1044

The problem here is that readlines() seems to read from the current file position on. If you first seek to the start of the temporary file, you will get the lines.

file.seek(0)
logging.debug(file.readlines())

Upvotes: 7

Related Questions