我提出了一个请求,并且能够访问和存储从页面下载的压缩文件。压缩文件包含内多个文本文件,如text1.txt
,text2.txt
等。
import requests
r = requests.get('http://somewhere.com/download.zip', stream=True)
handle = open('store_locally.zip', "wb")
for chunk in r.iter_content(chunk_size=512):
handle.write(chunk)
handle.close
但是,我想添加一个名为 .txt 的额外文件lastupdated.txt
。代码为:
import requests
r = requests.get('http://somewhere.com/download.zip', stream=True)
handle = open('store_locally.zip', "wb")
for chunk in r.iter_content(chunk_size=512):
handle.write(chunk)
f=open("lastupdated.txt","w+")
f.write('2019-02-12')
handle.write(f)
handle.close
这给了我以下错误:
Traceback (most recent call last):
File "C:\Users\main.py", line 55, in <module>
handle.write(f)
TypeError: a bytes-like object is required, not '_io.TextIOWrapper'
它确实lastupdated.txt
在 的同一目录中创建了文件main.py
,但这不是我想要的,我希望它在压缩文件中创建。
问题是你只是打开一个新文件 ( lastupdated.txt
) 并写入它,它与 zip 没有关系。将 zip 写入磁盘并关闭后,您可以使用该zipfile
模块将新文件添加到其中:
import zipfile
import requests
outfile = "stored_locally.zip"
r = requests.get("http://somewhere.com/download.zip", stream=True)
with open(outfile, "wb") as fd:
for chunk in r.iter_content(2048):
fd.write(chunk)
with zipfile.ZipFile(outfile, "a") as z:
z.writestr("lastupdated.txt", "2019-02-12")
编辑:在内存中下载和修改文件,而不写入磁盘:
import zipfile
from io import BytesIO
import requests
r = requests.get("http://somewhere.com/download.zip")
f = BytesIO(r.content)
with zipfile.ZipFile(f, "a") as z:
z.writestr("lastupdated.txt", "2019-02-12")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句