遍历目录h5文件的所有文件夹

我正在使用流行的百万首歌曲数据集,数据包含在几个嵌套的子文件夹中。所有文件均为.h5文件。我正在使用os库将数据导入python,但是它停在父文件夹中,并且不会循环获取所有数据。我不确定如何建立循环来实现这一目标。

entries = os.listdir("/Users/katherineperkins/Downloads/MillionSongSubset/data")



for filename in os.listdir(entries):
if filename.endswith(".h5") or filename.endswith(".py"): 
     # print(os.path.join(directory,filename))
    continue
else:
    continue

使用所有找到的代码段,我最终遇到以下错误:

listdir: path should be string,bytes,os.PathLike,integer or None,not list

owensun0306 回答:遍历目录h5文件的所有文件夹

entries是(目录?)名称的列表。 os.listdir不能同时将它们作为参数。您需要一个外部循环,而内部循环需要将条目与被扫描的目录连接起来。

root_dir = "/Users/katherineperkins/Downloads/MillionSongSubset/data"
for entry in os.listdir(root_dir):
   for filename in os.listdir(os.path.join(root_dir,entry)):
          if filename.endswith((".h5",".py")): 
              # do something: beware as filename isn't the full filepath.
              # it needs joining with os.path.join(root_dir,entry)

除非entry不是目录,否则以上代码均有效。我们可以测试目录,或捕获异常,或者有时可以使用两级“全文件”通配符切换到glob

import glob

for filepath in glob.glob("/Users/katherineperkins/Downloads/MillionSongSubset/data/*/*"):
      if filepath.endswith((".h5",".py")): 
          # do something

使用endswith(顺便接受tuple)测试文件扩展名的成本要比在两个扩展名上使用glob.glob(例如:glob.glob("/Users/katherineperkins/Downloads/MillionSongSubset/data/*/*.h5"))的花费要小(需要2个目录扫描)

本文链接:https://www.f2er.com/3135074.html

大家都在问