[英]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. 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)
,但它总是得到那个错误。 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 /
.这是由于os.getcwd()
没有返回尾随/
。
When you construct the path you send to cv2.imwrite
you concatenate two paths with no /
between them so you end up with:当您构造发送到cv2.imwrite
的路径时,您连接两条路径,它们之间没有/
,因此您最终得到:
"/a/path/from/getcwd" + "detected_car/car99.png"
Which results in a path that looks like this being sent to cv2.imwrite
:这导致看起来像这样的路径被发送到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.但是当你 go 删除文件时,你没有指定绝对路径,并要求os.remove
删除一个不存在的文件。
I can think of 2 ways of solving this:我可以想到两种解决方法:
current_path
:在current_path
中添加一个斜杠:current_path = os.getcwd() + "/"
cv2.imwrite
and os.remove
:对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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.