大家好我希望能够将一个单词列表传递给for循环,如何让代码在下面工作
list = ['word1','word2','word3']
for x in list
with open('folder/{x}.txt') as fin:
do something()
答案 0 :(得分:5)
这应该这样做:
word_list = ['word1','word2','word3']
for x in word_list:
with open('folder/{x}.txt'.format(x=x)) as fin:
do something()
我做了两个改变:
.format(x=x)
添加到字符串中。这是python的string interpolation机制答案 1 :(得分:-1)
你错过了冒号。 with
子句也需要一些工作。以下是如何在for
循环结束时修复冒号部分:
list = ['word1','word2','word3']
for x in list:
print(x)