使用列表中的项目创建文件名-for循环 [英] Using items in list to create file name - for loop
本文介绍了使用列表中的项目创建文件名-for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 我有一个用于循环的列表.
- 列表中的每个项目都有一个动作,但是我想为发生的事情写一个文件.
- 如何在for循环中使用变量为列表中的每个项目创建特定的文件名?
mylist = ['hello', 'there', 'world']
for i in mylist:
outputfile = open('%i.csv', 'a')
print('hello there moon', file=outputfile)
- 我是否在正确的轨道上使用
%i
代表列表中的单个项目?
mylist = ['hello', 'there', 'world']
for word in mylist:
with open('{}.csv'.format(word), 'a') as f_output:
print('hello there moon', file=f_output)
使用with
也会在之后自动关闭文件.
Using with
will also automatically close your file afterwards.
format()
具有许多可能的功能以允许进行各种字符串格式设置,但简单的情况是将{}
替换为参数,在您的情况下为word
.
format()
has many possible features to allow all kinds of string formatting, but the simple case is to replace a {}
with an argument, in your case a word
.
这篇关于使用列表中的项目创建文件名-for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文