强制python从不将文件刷新到dis

2024-04-16 15:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用request从url读取文件内容的场景。你知道吗

    f = open(..., 'wb')
    for chunk in message_content.iter_content():
        f.write(chunk)

但是,我不想实际将文件写入磁盘,因为我想继续操作我下载的f的内容。你知道吗

有没有办法告诉f永远不要写入磁盘?你知道吗


Tags: 文件inurl内容messageforrequest场景
2条回答

您可以使用^{}^{}而不是真正的file对象,因为它们的工作方式类似于file,只是它们将内容写入内存而不是file。你知道吗

f = io.BytesIO()   # Use `io.StringIO` if you want text mode (not binary mode)
for chunk in message_content.iter_content():
    f.write(chunk)

顺便说一句,您可以使用^{},而不是循环+write

writelines(lines) Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.

f.writelines(message_content.iter_content())

只需收集二进制对象中的所有块。不需要涉及文件。你知道吗

result = b''
for chunk in message_content.iter_content():
    result += chunk

或:

result = b''.join(message_content.iter_content())

相关问题 更多 >