在Python中使用请求下载多个文件

问题描述:

当前我面临以下问题:

我在列表中有3个下载链接.仅列表中的最后一个文件被完全下载.其他文件的大小为1 KB.

I have 3 download links in a list. Only the last file in the list is downloaded completely. The others have a file size of one kilobyte.

代码:

from requests import get

def download(url, filename):
    with open(filename, "wb") as file:
        response = get(url, stream=True)
        file.write(response.content)

for link in f:
    url = link
    split_url = url.split("/")
    filename = split_url[-1]
    filename = filename.replace("\n", "")
    download(url,filename)

结果如下:

结果

如何确保所有文件都正确下载?所有链接都是直接下载链接.

How do I make sure that all files are downloaded correctly? All links are direct download links.

提前谢谢!

我发现只有在读取.txt中的链接时才会发生

I discovered it only happens when I read the links from the .txt

如果我这样在p​​ython中创建列表:

If I create the list in python like this:

links = ["http://ipv4.download.thinkbroadband.com/20MB.zip",
            "http://ipv4.download.thinkbroadband.com/10MB.zip",
            "http://ipv4.download.thinkbroadband.com/5MB.zip"]

...问题没有出现.

... the problem doesnt appear.

可复制的示例:

from requests import get

def download(url, filename):
    with open(filename, "wb") as file:
        response = get(url, stream = True)
        file.write(response.content)

f = open('links.txt','r')
for link in f:
    url = link
    split_url = url.split("/")
    filename = split_url[-1]
    filename = filename.replace("\n", "")
    download(url,filename)

links.txt的内容:

content of links.txt:

http://ipv4.download.thinkbroadband.com/20MB.zip
http://ipv4.download.thinkbroadband.com/10MB.zip
http://ipv4.download.thinkbroadband.com/5MB.zip

url = url.replace("\ n",")

url = url.replace("\n", "")

解决了!