IsadirectoryError:[Errno 21]是一个目录:'/'解释
我从此代码中获得此错误。
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]是一个目录:'/'
^此错误是什么意思?我尝试谷歌搜索它,但在我的情况下仍然不了解。它与路径有关,但不确定为什么。
一切都会有帮助!
I am getting this error from this code.
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] Is a directory: '/'
^ what does this error mean? I tried googling it but still do not understand in my case. It has something to do with the paths but not sure why.
anything helps!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不做您认为做的事情。
它确实在给定目录中的所有文件上都不迭代迭代。使用 os.listdir 为此。您可以使用 os.path.join 。 pathlib module imho更简单地使用/更高级别的界面到所有级别的界面这。
您的代码的作用是在
os.path.abspath(path)
返回的字符串中迭代。第一个字符是/
。然后,您尝试将其作为文件打开。而且这是行不通的,因为/
是目录。doesn't do what you think it does.
It does not iterate over all files in a given directory. Use os.listdir for that. You can combine the directory path and the filename inside the directory using os.path.join. The pathlib module has an IMHO simpler to use / higher level interface to all of this.
What your code does is iterate over all characters in the string returned by
os.path.abspath(path)
. And the first character is/
. Which you then try to open as a file. And that doesn't work, because/
is a directory.您可能需要考虑在块中进行此操作,因为如果您的目录内容很大,则可能用完文件描述符。
这样的事情应该有效:
注意:
以提高效率,您应该考虑多线程
You might want to consider doing this in chunks because if your directory contents are very large, you could run out of file descriptors.
Something like this should work:
Note:
For improved efficiency you should consider multithreading for this
对于未来阅读此内容的人:
os.path.abspath(path)
为您提供一个字符串。在字符串上迭代意味着每个字符都已处理。OS.LISTDIR
仅给您相对路径(基本名称)。因此,您必须执行以下操作:或者您可以使用这样的列表进行理解:
For future people reading this:
os.path.abspath(path)
gives you a string. Iterating over a string means each character is handled.os.listdir
gives you only relative paths (base names). So you have to do the following:or you can use list-comprehension like this: