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

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

我得到了 Python: FileNotFoundError: [Errno 2]

我得到了 Python: FileNotFoundError: [Errno 2]

慕萊塢森 2022-10-25 15:18:03
我已經按順序生成圖像并保存在名為detected_car文件夾的目錄中,然后我想將它們發送到 JSON API 之類https://api.generate_json/的,當我從 API 獲得 json 響應時,它也會自動刪除os.remove("%s" %file),但它總是會出現該錯誤。這是我的代碼:import cv2import osimport jsonimport requestsimport timecar_count = [0]current_path = os.getcwd()file = 'detected_car/car' + str(len(car_count)) + ".png"path = '/home/username/Documents/path/to/image/dir%s' % fileresult = []def save_image(source_image):    cv2.imwrite(current_path + file , source_image)    car_count.insert(0, 1)    with open(path, 'rb') as fp:        response = request.post(            'https://api.generate_json/',            files=dict(upload=fp),            headers={'Authorization': 'Token ' + 'KEY_API'})        result.append(response.json())        print(json.dumps(result, indent=2));        with open('data.json', 'w') as outfile:            json.dump(result, outfile)    os.remove("%s" %file)    time.sleep(1)如何解決這個問題。謝謝你。
查看完整描述

1 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

您寫出的文件似乎保存在與您嘗試刪除的目錄不同的目錄中。這是由于os.getcwd()沒有返回尾隨/.


當您構建發送給cv2.imwrite您的路徑時,將兩條路徑連接/起來,它們之間沒有,因此您最終得到:


"/a/path/from/getcwd" + "detected_car/car99.png"

這導致看起來像這樣的路徑被發送到cv2.imwrite:


"/a/path/from/getcwddetected_car/car99.png"

但是當你去刪除文件時,你沒有指定絕對路徑,并要求os.remove刪除一個不存在的文件。


我可以想到兩種解決方法:


添加一個斜杠到current_path:

current_path = os.getcwd() + "/"

cv2.imwrite對和使用絕對路徑os.remove:

current_path = os.getcwd()

file = 'detected_car/car' + str(len(car_count)) + ".png"

temp_file = current_path + file


...


def save_image(source_image):

    cv2.imwrite(temp_file , source_image)


...


    os.remove("%s" %temp_file)


查看完整回答
反對 回復 2022-10-25
  • 1 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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