亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 269 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號