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 ?
{}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 towritelinesfunction.'{}\n'.format(item) for item in item_list. Note the format being applied inside the generator expression, not the other way around.