Python 如何在每次下载时重新创建文件夹?

Python 如何在每次下载时重新创建文件夹?,python,wget,shutil,python-os,Python,Wget,Shutil,Python Os,如果文件夹不存在,我想执行以下操作,然后创建它,但是如果我执行我的脚本(第二次)显然已经存在,因此我需要删除文件夹并下载其中的文件,但是我当前的脚本覆盖了该位置,并且demo变成了一个文件,我该怎么做 import os, shutil, wget base_path = os.path.dirname(os.path.abspath(__file__)) directory = os.path.join(base_path, 'demo') # check for extraction di

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

从pathlib导入路径
导入请求
DIR\u PATH=PATH(\uuuu文件\uuuu).parent/“demo”
#如果目录路径不存在,则创建目录路径
路径(DIR\u Path).mkdir(parents=True,exist\u ok=True)
URL=”https://github.com/facebookresearch/SING/blob/master/sing/nsynth/examples.json.gz?raw=true"
response=requests.get(URL,stream=True)
将open(f“{DIR_PATH}/example.json.gz”,“wb”)作为h:
对于响应中的数据。iter_content():
h、 写入(数据)
说明:
Path(_文件__)。parent
返回调用python脚本的目录(parent)。使用
pathlib
/
可以像在linux中一样使用。我们添加“demo”并在它不存在时创建它

使用请求,我们获取文件并使用流式处理将其放置到我们的文件夹中

要读取该文件,我们将解压它并将其加载到json

导入json
导入gzip
从pathlib导入路径
DIR\u PATH=PATH(\uuuu文件\uuuu).parent/“demo”
使用gzip.open(f“{DIR_PATH}/example.json.gz”,“rb”)作为gz:
json_data=json.load(gz)

检查目录是否存在,如果不存在则尝试创建它,会创建竞争条件:在
isdir
返回
False
之后,但在调用
makdirs
之前,其他进程可以创建它。更好的方法是调用
makedirs
,但忽略已存在的异常;尝试创建它,如果它已经存在,则忽略引发的异常。首先检查它是否存在的价值在于允许对目录名进行某种类型的命名递增,甚至有机会取消下载。然而,在大多数情况下,我同意这正是我所拥有的。我想创建if not exist>download,如果exist文件夹/文件,则使用shutil.rmtree(path)删除,然后重新创建如果我使用
wget.download
它将在每次下载时自动删除?使用
请求
或其他https库。查看更新
file_name = "new_file.ext" # Needs A file name!
# Otherwise we'll just overwrite the directory
if not os.path.exists(directory):
    os.makedirs(directory) # Create folder if it doesn't exist

file_location = os.path.join(directory, file_name) # Create the actual file location from our file name
remote_location = 'https://github.com/facebookresearch/SING/blob/master/sing/nsynth/examples.json.gz?raw=true'
try:
    wget.download(remote_location, out=file_location)
except:
    pass