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中的标识运算符
May 14 Python
Numpy中矩阵matrix读取一列的方法及数组和矩阵的相互转换实例
Jul 02 Python
Python tkinter label 更新方法
Oct 11 Python
解决pandas .to_excel不覆盖已有sheet的问题
Dec 10 Python
对python3 中方法各种参数和返回值详解
Dec 15 Python
python 怎样将dataframe中的字符串日期转化为日期的方法
Sep 26 Python
Python实现中值滤波去噪方式
Dec 18 Python
python tqdm 实现滚动条不上下滚动代码(保持一行内滚动)
Feb 19 Python
python生成大写32位uuid代码
Mar 03 Python
Python使用20行代码实现微信聊天机器人
Jun 05 Python
python判断一个变量是否已经设置的方法
Aug 13 Python
linux系统下pip升级报错的解决方法
Jan 31 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
一个可以删除字符串中HTML标记的PHP函数
2006/10/09 PHP
PHP内置的Math函数效率测试
2014/12/01 PHP
php实现的http请求封装示例
2016/11/08 PHP
centos 7.2下搭建LNMP环境教程
2016/11/20 PHP
PHP 二维关联数组根据其中一个字段排序(推荐)
2017/04/04 PHP
PHP批量删除jQuery操作
2017/07/23 PHP
php基于环形链表解决约瑟夫环问题示例
2017/11/07 PHP
tp5.1 框架数据库高级查询技巧实例总结
2020/05/25 PHP
js保留两位小数使用toFixed实现
2013/07/29 Javascript
JavaScript的继承的封装介绍
2013/10/15 Javascript
html文档中的location对象属性理解及常见的用法
2014/08/13 Javascript
PHP配置文件php.ini中打开错误报告的设置方法
2015/01/09 PHP
jquery实现点击弹出带标题栏的弹出层(从右上角飞入)效果
2015/09/19 Javascript
深入分析Javascript事件代理
2016/01/30 Javascript
jQuery实现为LI列表前3行设置样式的方法【2种方法】
2016/09/04 Javascript
jQuery图片前后对比插件beforeAfter用法示例【附demo源码下载】
2016/09/20 Javascript
基于node.js的fs核心模块读写文件操作(实例讲解)
2017/09/10 Javascript
Vue实现web分页组件详解
2017/11/28 Javascript
angular.js和vue.js中实现函数去抖示例(debounce)
2018/01/18 Javascript
解决layer弹层遮罩挡住窗体的问题
2018/08/17 Javascript
微信小程序HTTP接口请求封装代码实例
2019/09/05 Javascript
微信小程序开发(三):返回上一级页面并刷新操作示例【页面栈】
2020/06/01 Javascript
wxPython中文教程入门实例
2014/06/09 Python
跟老齐学Python之for循环语句
2014/10/02 Python
python递归删除指定目录及其所有内容的方法
2017/01/13 Python
Python实现计算两个时间之间相差天数的方法
2017/05/10 Python
Python中数组,列表:冒号的灵活用法介绍(np数组,列表倒序)
2018/04/18 Python
对PyQt5中的菜单栏和工具栏实例详解
2019/06/20 Python
详解Open Folder as PyCharm Project怎么添加的方法
2020/12/29 Python
CSS3+Sprite实现僵尸行走动画特效源码
2016/01/27 HTML / CSS
css3实现背景动态渐变效果
2019/12/10 HTML / CSS
什么是View State?
2013/01/27 面试题
2014年巴西世界杯口号
2014/06/05 职场文书
2015年行政助理工作总结
2015/04/30 职场文书
门面租赁合同范文
2019/08/06 职场文书
女性励志书籍推荐
2019/08/19 职场文书