Python根據(jù)URL地址下載文件并保存至對(duì)應(yīng)目錄的實(shí)現(xiàn)
引言
在編程中經(jīng)常會(huì)遇到圖片等數(shù)據(jù)集將圖片等數(shù)據(jù)以URL形式存儲(chǔ)在txt文檔中,為便于后續(xù)的分析,需要將其下載下來(lái),并按照文件夾分類存儲(chǔ)。本文以Github中Alexander Kim提供的圖片分類數(shù)據(jù)集為例,下載其提供的圖片樣本并分類保存
Python 3.6.5,Anaconda, VSCode
1. 下載數(shù)據(jù)集文件
建立項(xiàng)目文件夾,下載上述Github項(xiàng)目中的raw_data文件夾,并保存至項(xiàng)目目錄中。

2. 獲取樣本文件位置
編寫(xiě)get_doc_path.py,根據(jù)根目錄位置,獲取目錄及其子目錄所有數(shù)據(jù)集文件
import os
def get_file(root_path, all_files={}):
'''
遞歸函數(shù),遍歷該文檔目錄和子目錄下的所有文件,獲取其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 創(chuàng)建文件夾
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={}):
'''
遞歸函數(shù),遍歷該文檔目錄和子目錄下的所有文件,獲取其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 運(yùn)行結(jié)果
執(zhí)行get_pic.py
當(dāng)程序意外停止或再次執(zhí)行時(shí),程序會(huì)自動(dòng)跳過(guò)文件夾中已下載的文件,繼續(xù)下載未下載的內(nèi)容
{‘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
后注:由于樣本數(shù)據(jù)集內(nèi)容的問(wèn)題,上述地址以xxxxx代替具體地址,案例項(xiàng)目也已經(jīng)失效,但是方法仍然可以借鑒
20.9.23更新:數(shù)據(jù)集地址:https://github.com/ZQ-Qi/nsfw_data_scrapper,單純?yōu)榱藢W(xué)習(xí)和實(shí)踐本文代碼的可以下載該數(shù)據(jù)集進(jìn)行嘗試
到此這篇關(guān)于Python根據(jù)URL地址下載文件并保存至對(duì)應(yīng)目錄的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python URL下載文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python散列表(Hash Table)的實(shí)現(xiàn)示例
散列表是一種常用于實(shí)現(xiàn)關(guān)聯(lián)數(shù)組或映射的數(shù)據(jù)結(jié)構(gòu),本文我們將深入講解Python中的散列表,包括散列函數(shù)、沖突解決方法、散列表的實(shí)現(xiàn)和應(yīng)用場(chǎng)景,感興趣的可以了解一下2024-01-01
python實(shí)現(xiàn)簡(jiǎn)單的飛機(jī)大戰(zhàn)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡(jiǎn)單的飛機(jī)大戰(zhàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
pytorch 使用加載訓(xùn)練好的模型做inference
今天小編就為大家分享一篇pytorch 使用加載訓(xùn)練好的模型做inference,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
解決Python 函數(shù)聲明先后順序出現(xiàn)的問(wèn)題
這篇文章主要介紹了如何解決Python 函數(shù)聲明先后順序的問(wèn)題,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-09-09
Django中ModelForm組件的簡(jiǎn)單配置與使用教程
modelform是django中基于已有的model,快速生成的具有form功能的一個(gè)模塊,下面這篇文章主要給大家介紹了關(guān)于Django中ModelForm組件的簡(jiǎn)單配置與使用教程,需要的朋友可以參考下2022-10-10
創(chuàng)建SparkSession和sparkSQL的詳細(xì)過(guò)程
SparkSession 是 Spark SQL 的入口,Builder 是 SparkSession 的構(gòu)造器。 通過(guò) Builder, 可以添加各種配置,并通過(guò) stop 函數(shù)來(lái)停止 SparkSession,本文給大家分享創(chuàng)建SparkSession和sparkSQL的詳細(xì)過(guò)程,一起看看吧2021-08-08

