Python将数据保存到文件夹

我是 python 新手,我正在使用此代码下载图像,然后将其保存到与 python 文件相同的目录中。如何将它们保存到另一个文件夹?


def requesthandle( link, name ):

    global THREAD_COUNTER

    THREAD_COUNTER += 1

    try:

        r = requests.get( link, stream=True )

        if r.status_code == 200:

            r.raw.decode_content = True

           **Saving images**

            f = open( name, "wb" )

            shutil.copyfileobj(r.raw, f)

            f.close()

            print ("[*] Downloaded Image: %s" % name)

    except Exception as error:

        print ("[~] Error Occured with %s : %s" % (name, error))

    THREAD_COUNTER -= 1


慕尼黑5688855
浏览 269回答 2
2回答

DIEA

第一个参数open是文件的路径;如果只提供名称,则使用当前目录。因此,您只需将所需目录的路径(有 os.path 函数可以帮助解决此问题)添加到文件名中。

一只斗牛犬

首先你需要检查目录是否存在,如果不存在让我们创建一个而且您还需要更改文件的保存位置这是一个例子import osdef requesthandle( link, name ):    global THREAD_COUNTER    THREAD_COUNTER += 1    if not os.path.exists('/downloads'): #check if the folder is exist         os.makedir('/downloads') # if not let create one xD    try:        r = requests.get( link, stream=True )        if r.status_code == 200:            r.raw.decode_content = True            f = open( "/downloads/"+str(name) , "wb" ) # And here change where the file will be saved xD            shutil.copyfileobj(r.raw, f)            f.close()            print ("[*] Downloaded Image: %s" % name)    except Exception as error:        print ("[~] Error Occured with %s : %s" % (name, error))    THREAD_COUNTER -= 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python