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

问题描述 投票:2回答:1

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

    - 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文件并将它们放在地理数据库中。由于某种原因,它不会运行执行循环和复制的代码行。

python python-2.7 python-requests shutil arcpy
1个回答
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"
© www.soinside.com 2019 - 2024. All rights reserved.