如何使用glob访问多个子目录中的文件

发布于 2025-01-13 11:04:24 字数 423 浏览 3 评论 0原文

我有几个文件存储在名为 Originals 的文件夹中。 Originals 存储在名为 B_Substrate 的文件夹中,B_Substrate 存储在名为 Substrate_Training 的文件夹中,Substrate_Training 存储在名为 Jacob_Images 的文件夹中。

我正在尝试使用 glob 访问 Originals 文件夹中的文件,但无法访问它们。 任何人都可以帮助我了解如何访问多个子目录中的文件

这是我的代码,但它不起作用

import glob 
file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals/*.jpg'
for f in glob.glob(file):
    print(f)

I have several files stored in a folder called Originals. Originals is stored in a folder called B_Substrate, B_Substrate is stored in a folder called Substrate_Training and Substrate_Training is stored in a folder called Jacob_Images.

I am trying to access the files in the folder Originals using glob but unable to access them.
Can anyone help me understand how to access files in multiple sub directories

This is my code but it doesn't work

import glob 
file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals/*.jpg'
for f in glob.glob(file):
    print(f)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开浅夏 2025-01-20 11:04:24

不要在路径本身中指定 .jpg,而是在 glob() 函数中指定它。因此,您可以尝试以下操作:

import glob 
file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals'
for f in glob.glob(file + "/*.jpg"):
    print(f)

或者您可以使用下面的代码,借用这篇帖子中的代码。

for i in glob.glob('/home/studio-lab-user/sagemaker-studiolab-notebooks/Misc/tsv/**/*.csv', recursive=True):
    print(i)

你的代码也有效。我确信问题出在您提供的路径上。

使用您的方式:

Code 1

使用我的方式:

代码 2

Instead of specifying .jpg within the path itself, specify it in glob() function. So, you can try this:

import glob 
file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals'
for f in glob.glob(file + "/*.jpg"):
    print(f)

Or you can use this code below borrowing code from this post.

for i in glob.glob('/home/studio-lab-user/sagemaker-studiolab-notebooks/Misc/tsv/**/*.csv', recursive=True):
    print(i)

Your code also works. I am certain the issue is with the path you are providing.

Using your way:

Code 1

Using my way:

Code 2

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文