如何将文件夹名称声明为全局变量
下面的代码展示了第一步,我需要把输出文件夹声明为全局变量,这样后面的输出才能保存在这个文件夹里。目前我在输出文件夹的字符串 r'optfile/ras1' 这里遇到了错误。希望能得到一些帮助,教我怎么正确地存储文件到输出文件夹,并把它声明为全局变量。
import arcpy
import os
import pythonaddins
from datetime import datetime
now = datetime.now()
month = now.month
year = now.year
optfile = "C:/temp/"+str(year)+"_"+str(month)
class DrawRectangle(object):
"""Implementation for rectangle_addin.tool (Tool)"""
def __init__(self):
self.enabled = True
self.cursor = 1
self.shape = 'Rectangle'
os.makedirs(optfile)
def onRectangle(self, rectangle_geometry):
"""Occurs when the rectangle is drawn and the mouse button is released.
The rectangle is a extent object."""
extent = rectangle_geometry
arcpy.Clip_management(r'D:/test', "%f %f %f %f" %(extent.XMin, extent.YMin, extent.XMax, extent.YMax), r'optfile/ras1', "#", "#", "NONE")
arcpy.RefreshActiveView()
1 个回答
1
我想你是说,r'optfile/ras1'
这个值并没有使用到你的 optfile
变量。原因是 Python 并不会自动猜测你的意思,也不会替你把字符串中和变量名相同的部分替换掉。
你需要明确地使用 optfile
变量,把它和 /ras1
这部分连接起来:
arcpy.Clip_management(
r'D:/test',
"%f %f %f %f" %(extent.XMin, extent.YMin, extent.XMax, extent.YMax),
optfile + '/ras1', "#", "#", "NONE")
或者,更好的方法是使用 os.path.join()
函数,这样可以帮你处理路径中的分隔符:
import os.path
# ...
arcpy.Clip_management(
r'D:/test',
"%f %f %f %f" %(extent.XMin, extent.YMin, extent.XMax, extent.YMax),
os.path.join(optfile, 'ras1'), "#", "#", "NONE")
需要注意的是,你的问题和全局变量没有关系;这适用于你想要连接的变量来自哪里都一样。