Reputation: 195
I tried to write a output file from the values return from consecutively called functions but I couldnt make it instead I am getting error like below:
MA.write(l)
TypeError: expected a character buffer object
MY script:
def do():
print "Hello"
if __name__ == "__main__":
do()
MA=open("hi.txt","w")
l=map(lambda x: do(), range(10))
MA.write(l)
May be its basic but could someone give suggestions would be really helpful.
Expected OUTPUT:
hi.txt
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thanking you in advance
Upvotes: 0
Views: 45
Reputation: 6983
I think this is your intent:
def do():
return "Hello"
if __name__ == "__main__":
with open("hi.txt", "w") as adele:
hellos = map(lambda x: do(), range(10))
for hello in hellos:
adele.write(hello)
do()
needs to return a value to accumulate in the map
map
result in some wayOn the other hand, using the map
is overkill ... but maybe it makes sense in your larger context.
for x in range(10):
adele.write(do())
Upvotes: 2
Reputation: 2851
Try something like this:
def do():
return "Hello"
if __name__ == "__main__":
MA=open("hi.txt","w") # Prepare hi.txt
l=map(lambda x: do(), range(10)) # Adds Hello to the list 10 times
MA.write('\n'.join(l)) # Combines them together with a newline between each entry
MA.close() # Finished with hi.txt, this line is important
You need to return, not print your output to add it to the list, and then join each list entry into a single string to write with.
Changes I made from your version:
Upvotes: 1