2
  • I have a list that I am using for a for-loop.
  • Each item in the list has an action carried out, but I want to write a file for what has happened.
  • How can I use the variable in the for loop to create specific file names for each item in the list?
mylist = ['hello', 'there', 'world']
for i in mylist:
    outputfile = open('%i.csv', 'a')
    print('hello there moon', file=outputfile)
  • Am I on the right track using %i to represent individual items in the list?
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
StevieHyperB
  • 317
  • 1
  • 8
  • 18
  • Does this answer your question? [Creating a new file, filename contains loop variable, python](https://stackoverflow.com/questions/12560600/creating-a-new-file-filename-contains-loop-variable-python) – Trenton McKinney Jun 20 '20 at 20:28

5 Answers5

8

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.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
3

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()
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Jay Parikh
  • 2,419
  • 17
  • 13
2

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

outputfile = open('%s.csv' % i, 'a')
zanseb
  • 1,275
  • 10
  • 20
1
mylist = ['hello', 'there', 'world']
for item in mylist:
   with open('%s.txt'%item,'a') as in_file:
      in_file.write('hello there moon')
deepayan das
  • 1,567
  • 3
  • 14
  • 21
1

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')
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158