0

i am new on python, i wrote simple script to send all image sorted by time in folder to API. this code working on just one file(jpg), and can't send the rest of image in folder. I want to if i run this code, it's just waiting until some image added to current folder, when image is inside folder then it will send to API by time based on images that first existed. I am very confused, any helps will be appriciated! thx

import glob
import argparse
import requests
import json
import time
import os

def main():
    result = []

    file = glob.glob("/path/to/dir/*.jpg")

    regions = ['id']

    time_to_wait = 10000
    time_counter = 0

    while not os.path.exists(file):
        time.sleep(1)
        time_counter += 1
        if time_counter > time_to_wait: break
        print("waiting for file...")

        if os.path.isfile(file):
            with open(file, 'rb') as fp:
                response = requests.post(
                    'https://GET_API/',
                    data=dict(regions=regions),
                    files=dict(upload=fp),
                    headers={'Authorization': 'Token ' + 'XXX'})
                result.append(response.json())
                resp_dict = json.loads(json.dumps(result, indent=2))
                if resp_dict[0]['results']:
                    num=resp_dict[0]['results'][0]['plate']
                    print(f"DETECTED NUMBER:  {num}")
                os.remove(file)

    else:
        print("file doesn't exists!")

if __name__ == '__main__':
    main()

1 Answer 1

2

You didn't update your file on each iteration. Maybe that's why no more new files are detected. file also need to be treated as a list, so I guess you should iterate through file. Your while loop should look like this:

while True:
    files = glob.glob(os.path.join('path', 'to', 'dir', '*.jpg'))
    for file in files:
        if os.path.isfile(file):
            with open(file, 'rb') as fp:
                # Upload and delete
    # sleep
1
  • thankyou very much, i'm looking for this all day. thankyou! Jun 19, 2020 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.