繁体   English   中英

我得到了 Python: FileNotFoundError: [Errno 2] No such file or directory

[英]i got Python: FileNotFoundError: [Errno 2] No such file or directory

i have generated image in sequence and save in directory called detected_car folder, then i want to send them to JSON API like https://api.generate_json/ , when I get json response from API it's also delete automatic with os.remove("%s" %file) ,但它总是得到那个错误。 这是我的代码:

import cv2
import os
import json
import requests
import time

car_count = [0]
current_path = os.getcwd()
file = 'detected_car/car' + str(len(car_count)) + ".png"
path = '/home/username/Documents/path/to/image/dir%s' % file
result = []

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)

如何解决这个问题。 谢谢你。

您写出的文件似乎保存在与您尝试删除的目录不同的目录中。 这是由于os.getcwd()没有返回尾随/

当您构造发送到cv2.imwrite的路径时,您连接两条路径,它们之间没有/ ,因此您最终得到:

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

这导致看起来像这样的路径被发送到cv2.imwrite

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

但是当你 go 删除文件时,你没有指定绝对路径,并要求os.remove删除一个不存在的文件。

我可以想到两种解决方法:

  1. current_path中添加一个斜杠:
current_path = os.getcwd() + "/"
  1. cv2.imwriteos.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM