使用分割字符串命名文件

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

我正在从FGDB文件中提取照片,需要使用我们属性之一的部分名称来命名文件。通常,此脚本只接受属性并将它们连接起来,但是我需要做相反的事情,实际上是在第二个“-”处拆分单个属性,然后将第一个字符串用作文件名:

from arcpy import da
import os
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

inTable = arcpy.GetParameterAsText(0)
fileLocation = arcpy.GetParameterAsText(1)

with da.SearchCursor(inTable, ['DATA', 'ATT_NAME', 'ATTACHMENTID', 'PHOTO_NAME',]) as cursor:
    for item in cursor:
        attachment = item[0]
    filename = str(item[3]) 
        open(fileLocation + os.sep + filename, 'wb').write(attachment.tobytes())
        del item
        del filename
        del attachment

这是我正在使用的代码。我有点不知道从哪里开始。我应该在函数之前将其拆分并使其成为变量,还是将其包括在for循环中?

您可以看到,我对Python有点陌生,所以任何指针都可以帮助您

谢谢!

python arcgis blobstorage
1个回答
0
投票

我还没有测试过这段代码,但是可以正常工作吗?

with da.SearchCursor(inTable, ['DATA', 'ATT_NAME', 'ATTACHMENTID', 'PHOTO_NAME',]) as cursor:
    for item in cursor:
        attachment = item[0]

        string_to_split = str(item[3]) 
        # example: 'firstpart-secondpart-thirdpart'

        string_list = string_to_split.split('-') 
        # example: ['firstpart', 'secondpart', 'thirdpart']

        filename = string_list[0] + '-' + string_list[1]
        # example 'firstpart-secondpart' (probably also want a file extension here or on next line; .jpg perhaps)

        open(fileLocation + os.sep + filename, 'wb').write(attachment.tobytes())
        del item
        del filename
        del attachment
© www.soinside.com 2019 - 2024. All rights reserved.