Dhruv Ghulati Dhruv Ghulati - 1 year ago 74
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
should go with file
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 Source

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download