引言
在编程中经常会遇到图片等数据集将图片等数据以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("
"))