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?
1

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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

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

Comments

1
mylist = ['hello', 'there', 'world']
for item in mylist:
   with open('%s.txt'%item,'a') as in_file:
      in_file.write('hello there moon')

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.