รวมไฟล์ที่ขึ้นต้นด้วยอักขระเดียวกันโดยใช้ ArcPy

Aug 20 2020

ฉันกำลังพยายามรวมไฟล์ที่เริ่มต้นด้วย 2 ตัวอักษรเหมือนกันด้านล่าง

  1. 11111 - ผสาน (ชื่อเอาต์พุต: 11.shp)
  2. 11112 - ผสาน (ชื่อเอาต์พุต: 11.shp)
  3. 11113 - ผสาน (ชื่อเอาต์พุต: 11.shp)
  4. 22112 - ผสาน (ชื่อเอาต์พุต: 22.shp)
  5. 22153 - ผสาน (ชื่อเอาต์พุต: 22.shp)

แต่ผลลัพธ์ของสคริปต์ python ของฉันรวมเข้าด้วยกันถ้า "11" รวมอยู่ในชื่อไฟล์ (เช่น 4)) ฉันต้องการแค่ 11 ***. shp (1) ~ 3)) แต่ A Script จะรวม11 .shp (รวม 1 ~ 4 เป็น 11.shp)

================================================== ======================

import sys, os, arcpy, fnmatch
reload(sys)

arcpy.env.workspace  = r"F:\a"


workspace = arcpy.env.workspace
outdir = r"F:\b"

List = []

for dirpath, dirnames, filenames in os.walk(workspace, topdown=True):
    for filename in filenames:
        List.append(os.path.join(dirpath, filename))
    break

patterns = set([os.path.basename(fl)[:2] for fl in List])

for pattern in patterns:
    group = [fl for fl in List if fnmatch.fnmatchcase(fl, '*' + pattern + '*.shp')]
    output = os.path.join(outdir, pattern)
    arcpy.Merge_management(group, output)

================================================== ======================

จะแก้ไขได้อย่างไร?

คำตอบ

2 BERA Aug 20 2020 at 14:58

ฉันชอบcollection.defaultdict (รายการ) :

... เพื่อจัดกลุ่มลำดับของคู่คีย์ - ค่าลงในพจนานุกรมของรายการ

ตัวอย่าง:

import arcpy, os
from collections import defaultdict as dd

folder = r'C:\GIS\data\testdata\merge'
out_folder = r'C:\GIS\data\testdata\outfolder'

d = dd(list)

for item in os.listdir(folder):
    if os.path.isfile(os.path.join(folder,item)) and file.endswith('.shp'):
        d[item[:2]].append(os.path.join(folder, item))

#Execute code above then print(d) to make sure its ok before merging 

for group, mergelist in d.items():
    #print(group, mergelist)
    arcpy.Merge_management(inputs=mergelist, output=os.path.join(out_folder, 'Merge_{}.shp'.format(group)))

หากคุณต้องการค้นหาไดเรกทอรีย่อยเช่นกันให้ใช้ os.walk เหมือนที่คุณพยายามตัวอย่าง:

import os
from collections import defaultdict as dd

folder_main = r'C:\GIS\data\testdata'
d = dd(list)
for root, folder, files in os.walk(folder_main):
    for file in files:
        if os.path.isfile(os.path.join(root, file)) and file.endswith('.shp'):
            print(file)
            d[file[:2]].append(os.path.join(root, file))