python下载文件保存_Python根据URL地址下载文件并保存至对应目录的实现
引言
在编程中经常会遇到图片等数据集将图片等数据以URL形式存储在txt文档中,为便于后续的分析,需要将其下载下来,并按照文件夹分类存储。本文以Github中Alexander Kim提供的图片分类数据集为例,下载其提供的图片样本并分类保存
Python 3.6.5,Anaconda, VSCode
1. 下载数据集文件
建立项目文件夹,下载上述Github项目中的raw_data文件夹,并保存至项目目录中。
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根据URL地址下载文件并保存至对应目录的实现相关推荐
- python通过下载链接下载_Python根据URL地址下载文件——wget
爬虫过程中经常会需要下载一些资源,通常我们会使用request进行下载,方法大致如下 import requests # 请求链接,有防爬的要加headers,代理ip地址 img = request ...
- python根据url下载数据_利用Python如何实现根据URL地址下载并保存文件至对应目录...
利用Python如何实现根据URL地址下载并保存文件至对应目录 发布时间:2020-11-16 14:23:11 来源:亿速云 阅读:58 作者:Leah 这篇文章将为大家详细讲解有关利用Python ...
- Python根据URL地址下载文件并保存至对应目录
Python根据URL地址下载文件并保存至对应目录 引言 在编程中经常会遇到图片等数据集将图片等数据以URL形式存储在txt文档中,为便于后续的分析,需要将其下载下来,并按照文件夹分类存储.本文以Gi ...
- 火车头采集下载图片的位置和URL地址的更换
火车头采集下载图片的位置和URL地址的更换 1: 先明白, img 标签里面有一个 src 地址 2: 明白下面这图片的内容 下载图片勾选,是必须的 文件保存目录 它代表了2个意思 1是下载的位置[ ...
- Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
URL文件地址下载方法 一.正常情况下,我们都如此下载文件并修改文件名,在a标签上面添加download属性 //文件下载downFile() {if ('download' in document. ...
- python使用正则表达式检测给定的URL地址是否合法
python使用正则表达式检测给定的URL地址是否合法 # python使用正则表达式检测给定的URL地址是否合法 # python使用正则表达式检测给定的URL地址是否合法 # Check if a ...
- python下载邮件附件_Python - 从电子邮件附件下载excel文件然后解析它
编辑 - 更新 我创建了一个可怕的黑客,打开excel文件,然后使用相同的文件名将其保存下来,然后将excel文件打开到pandas中.这真的太可怕但我无法通过attachment.SaveFileA ...
- python 批量下载网页图片_Python实现多线程批量下载图片
<派森>(Python)3.13 win32 英文安装版 类型:编程工具大小:21M语言:英文 评分:8.7 标签: 立即下载 爬取图片可真的是一个可遇不可求的机会. 有需求就会动力. 目 ...
- java调用下载窗口_java 从网络Url中下载文件 java调用url接口
/** * 从网络Url中下载文件 * @param urlStr * @param fileName * @param savePath * @throws IOException */ publi ...
最新文章
- C++下的DLL编程入门
- 操作系统核心原理-5.内存管理(中):分页内存管理
- java多线程必杀技_Java技术大牛必备25个必杀技你都知道吗
- java===Runtime类
- 计算机分数的简便运算,分数的简便运算和分数的解方程
- java identifier expected,java – hibernate h2 embeddable list expected“identifier”
- MyBatis学习总结(19)——Mybatis传多个参数(三种解决方案)
- STM32串行驱动LCD12864显示屏程序代码
- 数据包络分析例题解析(含MATLAB代码)
- 旅游网站设计制作方案
- 烽火fr2600怎么web登录_烽火路由器回收,烽火交换机回收,烽火无线AP回收
- 《哪咤学python进阶篇》之选学案例三:白桦林的故事_(Python多媒体MV)
- 我们使用 Kafka 生产者在发消息的时候我们关注什么(Python 客户端 1.01 broker)...
- Debian AMD 64bit 折腾经历
- python迭代对象是什么意思_python的迭代对象
- VMware教程(二):CentOS 7 网络配置
- 使用idea构建父子类springboot项目教程,并教你启动子项目(构建项目集合)
- 关于android删除语音搜索功能的基本操作方法
- async/await的用法
- php中foreach 循环null,php中foreach循环问题
热门文章
- 解决CAD字体乱码或者显示?号,字体无法正常显示问题或将自己没有字体的dwg文件保存(转换)为已有的字体的dwg
- 《教练技术》读书笔记
- LaySNS插件—违规关键词检测插件
- 国行xboxone浏览 html5,国行XboxOne实体Xbox360游戏兼容性测试 并无限制
- 张驰咨询:六西格玛管理帮印刷线路板制造企业降低线路板层间短路
- 雅虎收购战的中国表情
- 船舶强度与结构设计大作业二matlab,船舶强度与结构设计最新版
- ROS不同工作空间下同名功能包下同名launch文件启动顺序问题(neither a launch file in package...)
- 人工智能AI到底能AI到什么程度?
- 牛仔激光烧花,牛仔激光洗水设备