【问题标题】:python 2.7 - How do I save images to a directory from a list of URLs in a CSV filepython 2.7 - 如何将图像从 CSV 文件中的 URL 列表保存到目录
【发布时间】:2014-09-01 07:55:53
【问题描述】:

我有一个包含两列的 CSV 文件,一个图像名称和一个图像 url...

示例

A 列 -- B 列

image1 -- http://www.image1.jpg

image2 -- http://www.image2.jpg

我正在尝试使用 Python 2.7 编写一个脚本,该脚本将 CSV 打开它并将图像保存到目录 c:\images,并使用与图像“image1”对应的图像名称命名它们,“ image2”等

到目前为止,我有以下代码:

import requests
import csv
import urllib2

images = csv.reader(open('image_urls.csv'))
for image in images:
    response = urllib2.urlopen(image[0])
    filename = 'image_{0}.{1}.jpg' 
    with open(filename,'wb') as w:
        w.write(response)
        w.close()

我有两个问题:

1) 我不确定如何将文件名正确保存为 CSV 第一列中的名称(“image1”)。

2) 按原样运行此代码会出现以下错误:

Traceback (most recent call last):
  File "downloadimages.py", line 11, in <module>
    w.write(response)
TypeError: must be string or buffer, not instance

谁能帮我修复错误和代码,以便按照我想要的方式保存文件名。

提前非常感谢。

【问题讨论】:

  • 您需要在响应时使用读取方法。 f=urllib2.urlopen(req) 然后回复=f.read()

标签: python image python-2.7 url csv


【解决方案1】:

你可以使用urllib中的urlretrieve传入位置来保存

from urllib import urlretrieve

with open ('image_urls.csv') as images:
    images = csv.reader(images)
    img_count = 1  # start at 1
    for image in images:
        urlretrieve(image[0],
                'c:\\images\\image_{0}.jpg'.format(img_count)) # string formatting inserting count 
        img_count += 1 # increase count for each image.

【讨论】:

    【解决方案2】:

    urllib2.urlopen 返回一个像对象而不是字符串的文件。所以你需要阅读它的内容:

    with open(filename,'wb') as w:
        w.write(response.read())
        w.close()
    

    【讨论】:

      猜你喜欢
      • 2016-05-09
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2013-03-05
      • 2021-07-04
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多