【问题标题】:Python TypeError: stat: path should be string, bytes, os.PathLike or integer, not listPython TypeError: stat: path should be string, bytes, os.PathLike or integer, not list
【发布时间】:2020-10-08 08:52:07
【问题描述】:

我是 python 新手,我编写了简单的脚本来将文件夹中按时间排序的所有图像发送到 API。此代码仅适用于一个文件(jpg),并且无法将其余图像发送到文件夹中。我想如果我运行这段代码,它只是等到一些图像添加到当前文件夹,当图像在文件夹内时,它将根据首先存在的图像按时间发送到 API。我很困惑,任何帮助都会得到帮助!谢谢

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()

【问题讨论】:

    标签: python image sorting time directory


    【解决方案1】:

    您没有在每次迭代时更新您的file。也许这就是为什么不再检测到新文件的原因。 file 也需要被视为一个列表,所以我想你应该遍历 file。您的 while 循环应如下所示:

    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
    

    【讨论】:

    • 非常感谢,我整天都在找这个。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 2018-12-23
    • 1970-01-01
    • 2020-11-07
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多