-3

我正在使用 python 2.7 和 arcpy 做一些数据管理。

我正在尝试创建一个脚本来询问用户数据来自哪一年,以便生成文件路径。

while True:
    try:
        year =  int(raw_input("What state fiscal year is this for (yyyy)? "))
    except ValueError:
        print("Are you daft?!")
        continue
    if year < 2017:
        print("Sorry tool is only compatible with post 2017 files")
    elif year > 2030:
        print("Someone needs to update the script... it's been over a decade since inception!")
    else:
        print("Party on!")
        break
scriptpath = os.getcwd()

下一行是用户输入进入文件路径的地方,也是抛出错误的行:

    folder = "OARS Raw Data\OARS S_FY{0}".format(year[2:])
Type error: 'int' object has no attribute '__ getitem __'

是什么导致它不拉年份值?我尝试分配另一个变量:year1 = year 在脚本路径和文件夹行之间,但仍然出现类型错误。

我应该提到当我在没有 while 循环的情况下分配年份时,文件夹行有效。year = "2018"

4

2 回答 2

1

对于使用切片,您需要先将其转换为字符串(例如):

folder = "OARS Raw Data\OARS S_FY{0}".format(str(year)[2:])

100或者只取最后 2 个数字的 mod :

folder = "OARS Raw Data\OARS S_FY{0}".format(year%100)
于 2018-06-22T15:51:11.150 回答
1

year是整数,而不是字符串。你不能切片整数:

>>> year = 2018
>>> year[2:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

首先将对象转换为字符串str(year)[2:]或者使用整数运算来获取最后两位数字:

folder = "OARS Raw Data\\OARS S_FY{0:02}".format(year % 100)

year % 100取一年的余数除以 100;所以最后两位数字:

>>> year % 100
18

请注意,我也更新了字符串模板,通过添加:02任何小于 10 的整数仍然0添加了前导:

>>> 'year: {0:02}'.format(9)
'year: 09'
于 2018-06-22T15:52:21.593 回答