简体   繁体   English

如何使用python从一个zip中的URL保存多个文件?

[英]How to save multiple file from URLs in one zip using python?

I am scrapping the files from URLs using beautiful soup, and then want to store those files in a single zip using Python. 我正在使用漂亮的汤从URL抓取文件,然后希望使用Python将这些文件存储在单个zip中。 Below is my code snippet for one URL. 以下是我针对一个网址的代码段。

fz = zipfile.ZipFile('C:\\Users\\ADMIN\\data\\data.zip', 'w')


response = urllib2.urlopen(url/file_name.txt)
file = open('C:\\Users\\ADMIN\\data\\filename.txt','w')
file.write(response.read())
file.close()

fz.write('C:\\Users\\ADMIN\\data\\filename.txt',compress_type=zipfile.ZIP_DEFLATED) fz.close()

This snippet is not working for me can any one please help me on this. 此代码段对我不起作用,任何人都可以帮助我。 getting below error: 低于错误:

WindowsError: [Error 2] The system cannot find the file specified: 'C:\\Users\\ADMIN\\data\\filename.txt' WindowsError:[错误2]系统找不到指定的文件:'C:\\ Users \\ ADMIN \\ data \\ filename.txt'

but file is present in this location. 但是该位置存在文件。

Use: 采用:

fz.writestr("file_name", url.read())

as many times as you need. 根据需要多次。 Ie one writestr() per file. 即每个文件一个writestr()。 Select the zip's mode (deflated) at the opening of the new ZIP. 在新ZIP的开头选择zip的模式(放气)。

So, you do not need to save file to disk, then pack it. 因此,您无需将文件保存到磁盘,然后打包。 Just get the html's name and the content and feed them to writestr(). 只需获取html的名称和内容并将其提供给writestr()。 ZIP gets '/' as a path separator. ZIP将'/'作为路径分隔符。 Therefore you use something like: "/some_dir/some_subdir/index.html" for subdirectories or "/index.html" to put a file into root. 因此,您可以使用诸如:“ / some_dir / some_subdir / index.html”作为子目录,或使用“ /index.html”将文件放入根目录。

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

相关问题 Python将多个目录压缩成一个zip文件 - Python zip multiple directories into one zip file 如何从多个URL导入python文件 - How to import python file from multiple urls 如何使用python将以下代码中生成的所有图像保存到Zip文件中? - How can I save all the generated images from the following code to a Zip file using python? 使用 Python 将多个 URL 中的不同变量抓取到一个 CSV 文件中 - Scraping different variables from multiple URLs into one single CSV file using Python 如何使用 Python 将 zip 中的文本文件解压缩为 zip - How to extract the text file from zip into zip using Python 如何在 python 中使用 docx 或 python-docx package 将多个 plotly 图保存在一个文档文件中 - How to save multiple plotly graphs in one document file using docx or python-docx package in python 如何使用 paramiko python 从 sftp 文件中解码 Zip 文件 - How to decode Zip file from sftp file using paramiko python 如何从多个URL读取Python中的HTML文件? - How do I read an HTML file in Python from multiple URLs? 如何从文本文件中读取 url 列表并将所有响应保存到一个文本文件中? - How can I read a list of urls from a text file and save all the responses into one text file? 如何使用 BeautifulSoup 从 txt 文件中使用多个 URL - How to use multiple URLs from a txt file using BeautifulSoup
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM