Python文本中的动态值

时间:2014-05-19 04:17:30

标签: python loops python-2.7

count = 1
maxcount = 6

while(count <= maxcount): 
    print locals()["test_"+str(count)]+str(".png")

    count += 1

我希望输出

test_1.png
test_2.png
test_3.png
test_4.png
test_5.png
test_6.png

相反,我收到错误

KeyError: 'test_1'

此外,如果值小于10,是否可以在0之后添加_

我正在使用此循环来保存文件,但认为这个MWE会减少劳动力并且很容易应用于我的问题

1 个答案:

答案 0 :(得分:3)

您收到该错误是因为您尚未在本地范围中创建名为“test_1”的变量。而不是使用while循环,使用for循环更容易。此外,还有一种称为字符串格式的东西,它比字符串连接更容易使用。

maxcount = 6
for i in range(1, maxcount+1):
    filename = 'test_{}.png'.format(i)
    with open(filename, 'r') as f:
        # do stuff