简体   繁体   English

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

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

I'm using python 3.6 on Windows 10, I want to download images so that their urls are stored in 1.txt file.我在 Windows 10 上使用 python 3.6,我想下载图像,以便它们的 url 存储在1.txt文件中。

This is my code:这是我的代码:

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)

but when I run the code above it gives me this error:但是当我运行上面的代码时,它给了我这个错误:

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 contains: test.txt包含:

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

When I tried to put just one single URL on test.txt , it works and downloaded the picture, but I need to download several images.当我试图在test.txt上只放置一个 URL 时,它可以工作并下载图片,但我需要下载多张图片。

f.readline() reads a single line from the file ; f.readline()从文件中读取一行 a newline character ( \\n ) is left at the end of the string, and is only omitted on the last line of the file if the file doesn't end in a newline.换行符 ( \\n ) 留在字符串的末尾,如果文件不以换行符结尾,则仅在文件的最后一行省略。

You are passing this filename (with \\n ) to open function(hence the OSError ).您正在传递此filename (带有\\n )以open函数(因此是OSError )。 So you need to call strip() on filename before passing into open .所以你需要在传入open之前对filename调用strip()

Your filename has the new line character ( \\n ) in it, remove that when you're parsing for the filename and it should fix your issue.您的文件名中包含换行符 ( \\n ),在解析文件名时将其删除,它应该可以解决您的问题。 It's working when you only have one file path in the txt file because there is only one line.当 txt 文件中只有一个文件路径时,它就可以工作,因为只有一行。

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

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