首页 > 解决方案 > 如何在每次下载时重新创建文件夹?

问题描述

如果文件夹不存在,我想执行以下操作然后创建它,但是如果我执行我的脚本(第二次)显然已经存在,所以我需要删除文件夹并下载里面的文件,但是我当前的脚本覆盖了位置,并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

标签: pythonwgetshutilpython-os

解决方案


使用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)

推荐阅读