python - 如何在每次下载时重新创建文件夹?
问题描述
如果文件夹不存在,我想执行以下操作然后创建它,但是如果我执行我的脚本(第二次)显然已经存在,所以我需要删除文件夹并下载里面的文件,但是我当前的脚本覆盖了位置,并demo
变成一个文件,我该怎么做?
import os, shutil, wget
base_path = os.path.dirname(os.path.abspath(__file__))
directory = os.path.join(base_path, 'demo')
# check for extraction directories existence
if not os.path.isdir(directory):
os.makedirs(directory)
else:
if os.path.exists(directory) and os.path.isdir(directory):
shutil.rmtree(directory)
#os.makedirs(directory)
remote_location = 'https://github.com/facebookresearch/SING/blob/master/sing/nsynth/examples.json.gz?raw=true'
try:
wget.download(remote_location, out=directory)
except:
pass
解决方案
使用pathlib
路径和文件夹时使用
from pathlib import Path
import requests
DIR_PATH = Path(__file__).parent / "demo"
# create dir_path if it does not exist
Path(DIR_PATH).mkdir(parents=True, exist_ok=True)
URL = "https://github.com/facebookresearch/SING/blob/master/sing/nsynth/examples.json.gz?raw=true"
response = requests.get(URL, stream=True)
with open(f"{DIR_PATH}/example.json.gz", "wb") as h:
for data in response.iter_content():
h.write(data)
解释:
Path(__file__).parent
返回调用 python 脚本的目录(父目录)。Withpathlib
/
习惯于在 linux 中使用。如果它不存在,我们添加“演示”并创建它。
使用请求,我们获取文件并使用流式传输将其放置到我们的文件夹中。
要读取文件,我们将其解压缩并加载到 json
import json
import gzip
from pathlib import Path
DIR_PATH = Path(__file__).parent / "demo"
with gzip.open(f"{DIR_PATH}/example.json.gz", 'rb') as gz:
json_data = json.load(gz)
推荐阅读
- javascript - 如何在 Angular 应用中使用 Telegram 授权
- java - 在 android 移动应用程序中测试应用内评论
- rust - 标准库所需的类型绑定的不满意的“默认”特征
- python - 在构建 conda 环境时可以使用 environment.yml 文件修剪不需要的包吗?
- excel - Excel Power Query:如何防止对同一源(web json)的多个请求?
- javascript - 如何搜索不在标题中的 Vuetify v-data-table 列?
- swift - 在 Swift 中无法识别轻按手势(手势开始)
- xml - 如何使用基于元素的条件删除 xml 节点
- struct - 在 presto 中提取数组数组
- c - 在 C 中开始字符串