为了账号安全,请及时绑定邮箱和手机立即绑定

Python将数据保存到文件夹

Python将数据保存到文件夹

慕尼黑5688855 2022-06-02 11:14:03
我是 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
查看完整描述

2 回答

?
DIEA

TA贡献1820条经验 获得超3个赞

第一个参数open是文件的路径;如果只提供名称,则使用当前目录。

因此,您只需将所需目录的路径(有 os.path 函数可以帮助解决此问题)添加到文件名中。


查看完整回答
反对 回复 2022-06-02
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

首先你需要检查目录是否存在,如果不存在让我们创建一个


而且您还需要更改文件的保存位置


这是一个例子


import os


def 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


查看完整回答
反对 回复 2022-06-02
  • 2 回答
  • 0 关注
  • 268 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号