IsADirectoryError: [Errno 21] 是一个目录: '/' 解释

问题描述 投票:0回答:2

我从这段代码中收到此错误。

import os
import requests
import shutil


path = "/Users/mycode/Documents/API upload/"


api_endpoint = "xxxxxx"


files = {
    'file': open(p,'rb') for p in os.path.abspath(path)
}

for file in os.path.abspath(path):
    response = requests.post(url=api_endpoint, files=files)
    if response.status_code == 200:
        print(response.status_code)
        print("success!")
    else:
        print("did not work")


IsADirectoryError:[Errno 21]是一个目录:'/'

^ 这个错误是什么意思?我尝试用谷歌搜索它,但仍然不明白我的情况。它与路径有关,但不确定为什么。

任何事情都有帮助!

python json file directory operating-system
2个回答
0
投票
for p in os.path.abspath(path)

没有做你认为的那样。

迭代给定目录中的所有文件。使用 os.listdir 来实现这一点。您可以使用 os.path.join 组合目录路径和目录内的文件名。 pathlib 模块 有一个恕我直言,更易于使用/更高级别的接口。

您的代码所做的是迭代

os.path.abspath(path)
返回的字符串中的所有字符。第一个字符是
/
。然后您尝试将其作为文件打开。但这是行不通的,因为
/
是一个目录。


0
投票

您可能需要考虑分块执行此操作,因为如果您的目录内容非常大,则可能会用完文件描述符。

这样的东西应该有效:

from requests import post
from glob import glob
from os.path import join, isfile

DIR = '/Users/mycode/Documents/API upload/'
CHUNK = 10
API_ENDPOINT = '...'

filelist = [filename for filename in glob(join(DIR, '*')) if isfile(filename)]

for idx in range(0, len(filelist), CHUNK):
    files = [('file', open(fn, 'rb')) for fn in filelist[idx:idx+CHUNK]]
    post(API_ENDPOINT, files=files).raise_for_status()
    for _, fd in files:
        fd.close()

注:

为了提高效率,您应该考虑使用多线程

© www.soinside.com 2019 - 2024. All rights reserved.