StevieHyperB
StevieHyperB

Reputation: 347

Using items in list to create file name - for loop

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

Upvotes: 2

Views: 4778

Answers (5)

Trenton McKinney
Trenton McKinney

Reputation: 62403

Use f-strings

Using code from OP

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()

Close the file using with

mylist = ['hello', 'there', 'world']
for i in mylist:

    with open(f'{i}.csv', 'a') as outputfile:

        outputfile.write('hello there moon')

Upvotes: 1

deepayan das
deepayan das

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

Martin Evans
Martin Evans

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

Jay Parikh
Jay Parikh

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

zanseb
zanseb

Reputation: 1425

You should use %s since the items in the list are strings.

outputfile = open('%s.csv' % i, 'a')

Upvotes: 2

Related Questions