繁体   English   中英

从存储在 .txt 文件中的 url 下载图像?

[英]Download images from url that is stored in .txt file?

我在 Windows 10 上使用 python 3.6,我想下载图像,以便它们的 url 存储在1.txt文件中。

这是我的代码:

import requests
import shutil

file_image_url = open("test.txt","r")
while True:
    image_url = file_image_url.readline()
    filename = image_url.split("/")[-1]
    r = requests.get(image_url, stream = True)
    r.raw.decode_content = True
    with open(filename,'wb') as f:
        shutil.copyfileobj(r.raw, f)

但是当我运行上面的代码时,它给了我这个错误:

Traceback (most recent call last):
File "download_pictures.py", line 10, in <module>
with open(filename,'wb') as f:
OSError: [Errno 22] Invalid argument: '03.jpg\n'

test.txt包含:

https://mysite/images/03.jpg
https://mysite/images/26.jpg
https://mysite/images/34.jpg

当我试图在test.txt上只放置一个 URL 时,它可以工作并下载图片,但我需要下载多张图片。

f.readline()从文件中读取一行 换行符 ( \\n ) 留在字符串的末尾,如果文件不以换行符结尾,则仅在文件的最后一行省略。

您正在传递此filename (带有\\n )以open函数(因此是OSError )。 所以你需要在传入open之前对filename调用strip()

您的文件名中包含换行符 ( \\n ),在解析文件名时将其删除,它应该可以解决您的问题。 当 txt 文件中只有一个文件路径时,它就可以工作,因为只有一行。

暂无
暂无

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

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