遍历子文件夹并复制具有特定扩展名的文件

时间:2018-09-26 15:26:56

标签: python python-2.7 python-requests shutil arcpy

我有一个父文件夹,我们称其为“工作区”。在此父文件夹中,有子文件夹,这些子文件夹包含具有特定命名约定的其他子文件夹。看起来像这样:

    - Workspace 
      - Subfolder A 
         - Name 
         - Image 
         - Class 
      - Subfolder B 
         - Name 
         - Image 
         - Class 
      - Subfolder C 
         - Name  
         - Image 
         - Class

我需要某种形式或方向的帮助,编写一个脚本,该脚本在工作区中通过A-C进行迭代,并将每个子文件夹的“ images”文件夹中的所有文件复制到新的目的地。

这是我到目前为止所拥有的:

import os
import arcpy
import shutil
import fnmatch

workspace = "source"
pfolder = "rootdir"

files = os.listdir(workspace)
print (files)

test = workspace + "\\scratch.gdb"
if os.path.exists(test):
    print ("Scratch GDB already exists")
    shutil.rmtree(test)
    scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
    print ("Original Scratch GDB removed and new GDB created ")
else:
    scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
    print ("Scratch GDB has been created")

def main():
        for dirname, dirnames, filenames in os.walk(pfolder):
            for file in filenames:
                if fnmatch.fnmatch(file,"*.jpg")==True:
                    shutil.copy2(file,scratch)
                    print("Files have been copied!")
                else:
                    print("Error in copying files")

我想复制该子目录中的所有jpg文件并将其放置在地理数据库中。由于某种原因,它不会运行执行循环和复制的代码行。

1 个答案:

答案 0 :(得分:0)

Shutil可能无法工作,无法在您cannot use the file extension in the name的地理数据库中输入栅格文件。

下面的代码是经过修改(例如,使用CopyRaster_management而不是copy2)进行工作的代码,因此它可能不是最佳代码,因为我对此并不担心,但是可以:

import os
import arcpy
import shutil
import fnmatch

workspace = "C:\\Teste\\"
pfolder = r'C:\Teste\\'

files = os.listdir(workspace)
print (files)

tests = workspace + "\\scratch.gdb"
sGdbP = "C:\\Teste\\scratch.gdb\\"
if os.path.exists(tests):
    print ("Scratch GDB already exists")
    shutil.rmtree(tests)
    scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
    print ("Original Scratch GDB removed and new GDB created ")
else:
    scratch = arcpy.CreateFileGDB_management(workspace,"scratch")
    print ("Scratch GDB has been created")

for dirname, dirnames, filenames in os.walk(pfolder):
    for file in filenames:
        if fnmatch.fnmatch(file,"*.tif")==True:
            try:
                arcpy.env.workspace = dirname
                in_data = file
                out_data = sGdbP + file[:-4] # cannot use extension
                arcpy.CopyRaster_management(in_data, out_data)
            except:
                print "Raster To Geodatabase example failed."
                print arcpy.GetMessages()
            print("Files have been copied!")

print "End of script"