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 相关文章推荐
python字符串排序方法
Aug 29 Python
Python实现大文件排序的方法
Jul 10 Python
Python实现自动登录百度空间的方法
Jun 10 Python
Python实现PS滤镜碎片特效功能示例
Jan 24 Python
python脚本作为Windows服务启动代码详解
Feb 11 Python
Python实现绘制双柱状图并显示数值功能示例
Jun 23 Python
Python实现全排列的打印
Aug 18 Python
tensorflow使用指定gpu的方法
Feb 04 Python
Python使用monkey.patch_all()解决协程阻塞问题
Apr 15 Python
使用Python实现音频双通道分离
Dec 25 Python
Python学习之迭代器详解
Apr 01 Python
python运行脚本文件的三种方法实例
Jun 25 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扩展imagick
2014/06/02 PHP
php去除html标记的原生函数详解
2015/01/27 PHP
Javascript常用字符串判断函数代码分享
2014/12/08 Javascript
JS实现网页每隔3秒弹出一次对话框的方法
2015/11/09 Javascript
基于jQuery实现点击弹出层实例代码
2016/01/01 Javascript
使用基于Node.js的构建工具Grunt来发布ASP.NET MVC项目
2016/02/15 Javascript
javascript数组去重小结
2016/03/07 Javascript
jQuery侧边栏实现代码
2016/05/06 Javascript
jQuery中的insertBefore(),insertAfter(),after(),before()区别介绍
2016/09/01 Javascript
聊一聊JS中的prototype
2016/09/29 Javascript
Vue.js实战之利用vue-router实现跳转页面
2017/04/01 Javascript
Node.js 利用cheerio制作简单的网页爬虫示例
2018/03/01 Javascript
小程序实现横向滑动日历效果
2019/10/21 Javascript
如何实现小程序与小程序之间的跳转
2020/11/04 Javascript
详解Python中内置的NotImplemented类型的用法
2015/03/31 Python
python运行时间的几种方法
2016/06/17 Python
Python AES加密模块用法分析
2017/05/22 Python
Python批处理删除和重命名文件夹的实例
2018/07/11 Python
python多行字符串拼接使用小括号的方法
2020/03/19 Python
java中的控制结构(if,循环)详解
2019/06/26 Python
Python创建一个元素都为0的列表实例
2019/11/28 Python
Python插入Elasticsearch操作方法解析
2020/01/19 Python
python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例
2020/03/10 Python
详解HTML5中div和section以及article的区别
2015/07/14 HTML / CSS
Stutterheim瑞典:瑞典高级外套时装品牌
2019/06/24 全球购物
英国电子产品购物网站:Tech in the basket
2019/11/08 全球购物
不假外出检讨书
2014/01/27 职场文书
《生命 生命》教学反思
2014/04/19 职场文书
2014高考励志标语
2014/06/05 职场文书
某集团股份有限公司委托书样本
2014/09/24 职场文书
2014年安全员工作总结
2014/11/13 职场文书
中学后勤工作总结2015
2015/07/22 职场文书
golang 实现菜单树的生成方式
2021/04/28 Golang
Vue Element UI自定义描述列表组件
2021/05/18 Vue.js
游戏《我的世界》澄清Xbox版暂无计划加入光追
2022/04/03 其他游戏
Windows和Linux上部署Golang并运行程序
2022/04/22 Servers