python如何将数组值传递到文件打开请求中

2024-03-28 16:10:00 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我想能够通过一个单词列表进入for循环,我如何才能使下面的代码工作

list = ['word1','word2','word3']
for x in list
      with open('folder/{x}.txt') as fin:
      do something()

Tags: 代码intxt列表foraswithopen
2条回答

这应该做到:

word_list = ['word1','word2','word3']
for x in word_list:
    with open('folder/{x}.txt'.format(x=x)) as fin:
         do something()

我做了两个改变:

  • 在for语句后添加一个忘记的冒号
  • .format(x=x)添加到字符串中。这是python的string interpolation机制

你少了一个冒号。with子句也需要一些工作。下面是如何修复for循环末尾的冒号部分:

list = ['word1','word2','word3']
for x in list:
    print(x)

相关问题 更多 >