简体   繁体   中英

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) , but it's always get that error. this is my code:

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)

how to solve this. thankyou.

The file you write out appears to be saved into a different directory than the one you try to remove. This is due to os.getcwd() not returning a trailing / .

When you construct the path you send to cv2.imwrite you concatenate two paths with no / between them so you end up with:

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

Which results in a path that looks like this being sent to cv2.imwrite :

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

But when you go to remove the file, you don't specify the absolute path, and ask os.remove to delete a file that doesn't exist.

I can think of 2 ways of solving this:

  1. Add a trailing slash to current_path :
current_path = os.getcwd() + "/"
  1. Use an absolute path for both cv2.imwrite and 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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