Dhruv Ghulati Dhruv Ghulati - 9 months ago 32
Python Question

Using `map` to write lines to files

I have a list of lines:

lines = [a,b,c,d]


And a list of files (created via
open(path string,'w')
:

files = [e,f,g,h]


What I am trying to do is write each line to its respective file (line
a
should go with file
e
and a new line). Note, this is all part of a much larger loop to generate the lines and put them in this list of lines you see:

This is my current method:

map(lambda (x,y): y.write(x) + "\n",zip(lines,files))


But this is what I am getting:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'


What is a way of achieving what I need? Writing each line to each file separately is very cumbersome.

Answer

Did you mean to do:

map(lambda (x,y): y.write(x + "\n"), zip(lines,files))

But I'd rather do it as:

for l, f in zip(lines,files):
    f.write(l + "\n")