Reputation: 347
mylist = ['hello', 'there', 'world']
for i in mylist:
outputfile = open('%i.csv', 'a')
print('hello there moon', file=outputfile)
%i
to represent individual items in the list?Upvotes: 2
Views: 4778
Reputation: 62403
f
and the variable is inside the string quotes, surrounded by {}
.
f'{i}.csv'
mylist = ['hello', 'there', 'world']
for i in mylist:
# open the file
outputfile = open(f'{i}.csv', 'a')
# write to the file
print('hello there moon', file=outputfile)
# close the file
outputfile.close()
with
mylist = ['hello', 'there', 'world']
for i in mylist:
with open(f'{i}.csv', 'a') as outputfile:
outputfile.write('hello there moon')
Upvotes: 1
Reputation: 1657
mylist = ['hello', 'there', 'world']
for item in mylist:
with open('%s.txt'%item,'a') as in_file:
in_file.write('hello there moon')
Upvotes: 1
Reputation: 46759
You can use format()
to do what you need as follows:
mylist = ['hello', 'there', 'world']
for word in mylist:
with open('{}.csv'.format(word), 'a') as f_output:
print('hello there moon', file=f_output)
Using with
will also automatically close your file afterwards.
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
.
Upvotes: 8
Reputation: 2489
Use following code.
mylist = ['hello', 'there', 'world']
for i in mylist:
outputfile = open('%s.csv'%i, 'a')
print('hello there moon', file=outputfile)
outputfile.close()
Upvotes: 3
Reputation: 1425
You should use %s
since the items in the list are strings.
outputfile = open('%s.csv' % i, 'a')
Upvotes: 2