【问题标题】:Loop through subfolder and copy file with specific extension遍历子文件夹并复制具有特定扩展名的文件
【发布时间】:2019-03-02 10:38:45
【问题描述】:

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

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

【问题讨论】:

  • 你在哪里调用你的main函数?

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


【解决方案1】:

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多