Python根据URL地址下载文件并保存至对应目录的实现


Posted in Python onNovember 15, 2020

引言

在编程中经常会遇到图片等数据集将图片等数据以URL形式存储在txt文档中,为便于后续的分析,需要将其下载下来,并按照文件夹分类存储。本文以Github中Alexander Kim提供的图片分类数据集为例,下载其提供的图片样本并分类保存

Python 3.6.5,Anaconda, VSCode

1. 下载数据集文件

建立项目文件夹,下载上述Github项目中的raw_data文件夹,并保存至项目目录中。

Python根据URL地址下载文件并保存至对应目录的实现

 2. 获取样本文件位置

编写get_doc_path.py,根据根目录位置,获取目录及其子目录所有数据集文件

import os


def get_file(root_path, all_files={}):
  '''
  递归函数,遍历该文档目录和子目录下的所有文件,获取其path
  '''
  files = os.listdir(root_path)
  for file in files:
    if not os.path.isdir(root_path + '/' + file):  # not a dir
      all_files[file] = root_path + '/' + file
    else: # is a dir
      get_file((root_path+'/'+file), all_files)
  return all_files


if __name__ == '__main__':
  path = './raw_data'
  print(get_file(path))

3. 下载文件

3.1 读取url列表并

for filename, path in paths.items():
    print('reading file: {}'.format(filename))
    with open(path, 'r') as f:
      lines = f.readlines()
      url_list = []
      for line in lines:
        url_list.append(line.strip('\n'))
      print(url_list)

3.2 创建文件夹

foldername = "./picture_get_by_url/pic_download/{}".format(filename.split('.')[0])
if not os.path.exists(folder_path):
    print("Selected folder not exist, try to create it.")
    os.makedirs(folder_path)

3.3 下载图片

def get_pic_by_url(folder_path, lists):
  if not os.path.exists(folder_path):
    print("Selected folder not exist, try to create it.")
    os.makedirs(folder_path)
  for url in lists:
    print("Try downloading file: {}".format(url))
    filename = url.split('/')[-1]
    filepath = folder_path + '/' + filename
    if os.path.exists(filepath):
      print("File have already exist. skip")
    else:
      try:
        urllib.request.urlretrieve(url, filename=filepath)
      except Exception as e:
        print("Error occurred when downloading file, error message:")
        print(e)

4. 完整源码

4.1 get_doc_path.py

import os


def get_file(root_path, all_files={}):
  '''
  递归函数,遍历该文档目录和子目录下的所有文件,获取其path
  '''
  files = os.listdir(root_path)
  for file in files:
    if not os.path.isdir(root_path + '/' + file):  # not a dir
      all_files[file] = root_path + '/' + file
    else: # is a dir
      get_file((root_path+'/'+file), all_files)
  return all_files


if __name__ == '__main__':
  path = './raw_data'
  print(get_file(path))

4.2 get_pic.py

import get_doc_path
import os
import urllib.request


def get_pic_by_url(folder_path, lists):
  if not os.path.exists(folder_path):
    print("Selected folder not exist, try to create it.")
    os.makedirs(folder_path)
  for url in lists:
    print("Try downloading file: {}".format(url))
    filename = url.split('/')[-1]
    filepath = folder_path + '/' + filename
    if os.path.exists(filepath):
      print("File have already exist. skip")
    else:
      try:
        urllib.request.urlretrieve(url, filename=filepath)
      except Exception as e:
        print("Error occurred when downloading file, error message:")
        print(e)


if __name__ == "__main__":
  root_path = './picture_get_by_url/raw_data'
  paths = get_doc_path.get_file(root_path)
  print(paths)
  for filename, path in paths.items():
    print('reading file: {}'.format(filename))
    with open(path, 'r') as f:
      lines = f.readlines()
      url_list = []
      for line in lines:
        url_list.append(line.strip('\n'))
      foldername = "./picture_get_by_url/pic_download/{}".format(filename.split('.')[0])
      get_pic_by_url(foldername, url_list)

4.3 运行结果

执行get_pic.py
当程序意外停止或再次执行时,程序会自动跳过文件夹中已下载的文件,继续下载未下载的内容

{‘urls_drawings.txt': ‘./picture_get_by_url/raw_data/drawings/urls_drawings.txt', ‘urls_hentai.txt': ‘./picture_get_by_url/raw_data/hentai/urls_hentai.txt', ‘urls_neutral.txt': ‘./picture_get_by_url/raw_data/neutral/urls_neutral.txt', ‘urls_porn.txt': ‘./picture_get_by_url/raw_data/porn/urls_porn.txt', ‘urls_sexy.txt': ‘./picture_get_by_url/raw_data/sexy/urls_sexy.txt'}
reading file: urls_drawings.txt
Try downloading file: http://41.media.tumblr.com/xxxxxx.jpg
Try downloading file: http://41.media.tumblr.com/xxxxxx.jpg
Try downloading file: http://ak1.polyvoreimg.com/cgi/img-thing/size/l/tid/xxxxxx.jpg
Error occurred when downloading file, error message:
HTTP Error 502: No data received from server or forwarder
Try downloading file: http://akicocotte.weblike.jp/gaugau/xxxxxx.jpg
Try downloading file: http://animewriter.files.wordpress.com/2009/01/nagisa-xxxxxx-xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg
Try downloading file: http://cdn.awwni.me/xxxxxx.jpg

后注:由于样本数据集内容的问题,上述地址以xxxxx代替具体地址,案例项目也已经失效,但是方法仍然可以借鉴

20.9.23更新:数据集地址:https://github.com/ZQ-Qi/nsfw_data_scrapper,单纯为了学习和实践本文代码的可以下载该数据集进行尝试

到此这篇关于Python根据URL地址下载文件并保存至对应目录的实现的文章就介绍到这了,更多相关Python URL下载文件内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python3通过Luhn算法快速验证信用卡卡号的方法
May 14 Python
Python去除字符串两端空格的方法
May 21 Python
各种Python库安装包下载地址与安装过程详细介绍(Windows版)
Nov 02 Python
Python编程实现的简单Web服务器示例
Jun 22 Python
python爬虫headers设置后无效的解决方法
Oct 21 Python
python实现京东秒杀功能
Jul 30 Python
Flask Web开发入门之文件上传(八)
Aug 17 Python
python字典嵌套字典的情况下找到某个key的value详解
Jul 10 Python
python被修饰的函数消失问题解决(基于wraps函数)
Nov 04 Python
python中删除某个元素的方法解析
Nov 05 Python
浅谈matplotlib.pyplot与axes的关系
Mar 06 Python
Django 用户登陆访问限制实例 @login_required
May 13 Python
python re的findall和finditer的区别详解
Nov 15 #Python
Python获取android设备cpu和内存占用情况
Nov 15 #Python
Python __slots__的使用方法
Nov 15 #Python
Python descriptor(描述符)的实现
Nov 15 #Python
基于OpenCV的网络实时视频流传输的实现
Nov 15 #Python
彻底解决Python包下载慢问题
Nov 15 #Python
Python eval函数原理及用法解析
Nov 14 #Python
You might like
解析php根据ip查询所在地区(非常有用,赶集网就用到)
2013/07/01 PHP
php发送get、post请求的6种方法简明总结
2014/07/08 PHP
Thinkphp调用Image类生成缩略图的方法
2015/03/07 PHP
thinkPHP3.1验证码的简单实现方法
2016/04/22 PHP
php微信公众平台示例代码分析(二)
2016/12/06 PHP
Yii2实现增删改查后留在当前页的方法详解
2017/01/13 PHP
php 调用ffmpeg获取视频信息的简单实现
2017/04/03 PHP
Laravel 错误提示本地化的实现
2019/10/22 PHP
cssQuery()的下载与使用方法
2007/01/12 Javascript
javaScript 判断字符串是否为数字的简单方法
2009/07/25 Javascript
使用隐藏的new来创建对象
2011/03/29 Javascript
js面向对象实现canvas制作彩虹球喷枪效果
2016/09/24 Javascript
详解Vue.js——60分钟组件快速入门(上篇)
2016/12/05 Javascript
微信小程序开发教程-手势解锁实例
2017/01/06 Javascript
基于bootstrap按钮式下拉菜单组件的搜索建议插件
2017/03/25 Javascript
Vue父子模版传值及组件传值的三种方法
2017/11/27 Javascript
Vue cli+mui 区域滚动的实例代码
2018/01/25 Javascript
浅谈VUE-CLI脚手架热更新太慢的原因和解决方法
2018/09/28 Javascript
JS监听事件的叠加和移除功能
2018/11/19 Javascript
NodeJs实现简易WEB上传下载服务器
2019/08/10 NodeJs
基于NodeJS开发钉钉回调接口实现AES-CBC加解密
2020/08/20 NodeJs
在python2.7中用numpy.reshape 对图像进行切割的方法
2018/12/05 Python
超简单使用Python换脸实例
2019/03/27 Python
Django框架实现的分页demo示例
2019/05/25 Python
Python socket连接中的粘包、精确传输问题实例分析
2020/03/24 Python
Mansur Gavriel官网:纽约市的一个设计品牌
2019/05/02 全球购物
Michael Kors澳大利亚官网:世界知名的奢侈饰品和成衣设计师
2020/02/13 全球购物
汽车技术服务与营销专业在籍生自荐信
2013/09/28 职场文书
大学生入党思想汇报
2014/01/14 职场文书
yy婚礼司仪主持词
2014/03/14 职场文书
2014年挂职干部工作总结
2014/12/06 职场文书
2014年图书馆个人工作总结
2014/12/18 职场文书
承诺书范本
2015/01/21 职场文书
鲁迅故居导游词
2015/02/05 职场文书
如何用threejs实现实时多边形折射
2021/05/07 Javascript
Java新手教程之ArrayList的基本使用
2021/06/20 Java/Android