user3805057
user3805057

Reputation: 195

How to write an output file of multiple time called functions?

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

Answers (2)

rrauenza
rrauenza

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
  • you need to iterate over your map result in some way

On 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

rp.beltran
rp.beltran

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:

  • I return "hello" instead of printing it
  • I don't run do() right away,because you don't need to.
  • I combine the elements before writing them
  • I close the file when I am done

Upvotes: 1

Related Questions