3

I am trying to write a list to a file. When I use the following code it gives me an error :

    with open('list.txt', 'w') as fref :
        fref.writelines('{}\n'.format(item for item in item_list))

But when I modify the code to :

    with open('list.txt', 'w') as fref :
        for item in item_list :
            fref.writelines('{}\n'.format(item))

or

when I format the string using % :

    with open('list.txt', 'w') as fref :
        fref.writelines('%s\n' % item for item in item_list)

it works fine. I am confused as to why does the for loop inside the format method fail ?

2
  • 3
    {} is a position based format. You cant provide multiple strings for one position. If you check the 3rd one. It's same as the 2nd one, you are just passing multiple lines to writelines function. Commented May 24, 2020 at 7:23
  • The equivalent format expression for the latter two is '{}\n'.format(item) for item in item_list. Note the format being applied inside the generator expression, not the other way around. Commented May 24, 2020 at 7:38

1 Answer 1

4
    with open('list.txt', 'w') as fref :
        fref.writelines('%s\n' % item for item in item_list)

Can be read as (note the parenthesis):

    with open('list.txt', 'w') as fref :
        fref.writelines(('%s\n' % item) for item in item_list)

You pass file.writelines a generator expression, in which each item is a formatted string.

While:

    with open('list.txt', 'w') as fref :
        fref.writelines('{}\n'.format(item for item in item_list))

Creates a generator expression of arguments, that will be sent 1 time to the str.format method.

Instead, create a generator expression which calls str.format for each item in item_list:

    with open('list.txt', 'w') as fref :
        fref.writelines('{}\n'.format(item) for item in item_list)

Now file.writelines receives generator expression of strings as an argument.

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

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.