【问题标题】:loop through sub directories, to sample files循环遍历子目录,以示例文件
【发布时间】:2016-06-28 19:09:43
【问题描述】:

以下代码从目录 1 中随机选择文件样本(本例中为 50 个)并将它们复制到同名的新文件夹中。

但是,我需要从中采样数百个文件夹(并复制到同名的新文件夹)。

如何调整代码的第一部分,以便循环遍历所有子目录,并将示例移动到具有相同名称的新文件夹中。 (所以子目录1的样本到目录1,子目录2的样本到目录2 等等)

import os 
import shutil 
import random 
from shutil import copyfile

sourcedir = '/home/mrman/dataset-python/train/1/'
newdir  = '/home/mrman/dataset-python/sub-train/1'


filenames = random.sample(os.listdir(sourcedir), 50)
for i in filenames:
    shutil.copy2(sourcedir + i, newdir)

【问题讨论】:

    标签: python loops mkdir subdirectory


    【解决方案1】:

    您希望使用os.walk。查看documentation

    运行以下命令以了解其工作原理,并阅读文档以了解如何将其用于您的解决方案。最终,将会发生的是,您将从您提供的路径遍历整个目录结构,并且每次迭代都会为您提供您所在的当前路径、该级别中的所有目录以及所有文件。

    另外,假设您想对某事物的特定完整路径进行操作,然后确保在创建路径时利用os.path.join

    your_path = "/some/path/you/want"
    for path, dirs, files in os.walk(your_path):
        print(path)
        print(dirs)
        print(files)
    

    【讨论】:

      【解决方案2】:

      解决方案比预期的要简单(感谢@idjaw 的提示):

      import os, sys
      import shutil
      import random
      from shutil import copyfile
      
      #folder which contains the sub directories
      source_dir = '/home/mrman/dataset-python/train/'
      
      #list sub directories 
      for root, dirs, files in os.walk(source_dir):
      
      #iterate through them
          for i in dirs: 
      
              #create a new folder with the name of the iterated sub dir
              path = '/home/mrman/dataset-python/sub-train/' + "%s/" % i
              os.makedirs(path)
      
              #take random sample, here 3 files per sub dir
              filenames = random.sample(os.listdir('/home/mrman/dataset-python/train/' + "%s/" % i ), 3)
      
              #copy the files to the new destination
              for j in filenames:
                  shutil.copy2('/home/mrman/dataset-python/train/' + "%s/" % i  + j, path)
      

      【讨论】:

      • 干得好!搞清楚这件事做得很好。 +1
      • 既然你已经弄清楚了,你应该接受这个解决方案来表明它已经解决了。
      • 再次感谢!由于我是新手,我必须等待两天才能接受它:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2020-11-05
      • 2013-09-20
      • 1970-01-01
      相关资源
      最近更新 更多