简体   繁体   English

写入后无法从NamedTemporaryFile中读取

[英]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. 我使用NamedTemporaryFile尝试过此操作,但是我被迫关闭文件并重新打开它。

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. 如果我在with块外重新打开该文件并尝试读取该文件,则该文件可以正常工作。 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. 我是python开发人员中的新手。

The problem here is that readlines() seems to read from the current file position on. 这里的问题是readlines()似乎是从当前文件位置开始读取的。 If you first seek to the start of the temporary file, you will get the lines. 如果您首先寻求临时文件的开始,那么您将获得这些行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM