使用列表中的项目创建文件名 - for循环

Ste*_*erB 2 python variables loops for-loop

对Python来说仍然是新手,所以可能很容易回答.

我有一个列表,我用于for循环.因此,列表中的每个项目都执行了一个操作,但我想为已发生的事情编写一个文件,如何在for循环中使用该变量为列表中的每个项目创建特定的文件名,所以在mo我有这样的事情;

mylist = ['hello', 'there', 'world']
for i in mylist:
  outputfile = open('%i.csv', 'a')
  print('hello there moon', file=outputfile)
Run Code Online (Sandbox Code Playgroud)

我是否在正确的轨道上使用%i代表列表中的单个项目?

Mar*_*ans 8

您可以format()按照以下方式使用所需的操作:

mylist = ['hello', 'there', 'world']

for word in mylist:
    with open('{}.csv'.format(word), 'a') as f_output:
        print('hello there moon', file=f_output)    
Run Code Online (Sandbox Code Playgroud)

使用后with也会自动关闭您的文件.

format()有许多可能的功能允许各种字符串格式化,但简单的情况是{}用一个参数替换a ,在你的情况下a word.