Home > database >  Writing None in a file using python
Writing None in a file using python

Time:03-25

I'm trying to put the output in a new file

with open('INFO', 'a') as x:
        x.write(main())

But I got this error

x.write(main())
TypeError: write() argument must be str, not None

When I write

with open('INFO', 'a') as x:
        x.write(str(main()))

In the file I got only this

None

how can I fix it? plz help

CodePudding user response:

It seems as though main() does not return anything. This is normal Python behavior, make sure you added a return statement.

CodePudding user response:

Write function accepts a string as arguement i.e

with open('INFO', 'a') as x:
    x.write('Hello')

will write the string "Hello" to the INFO file. The reason you're getting an error is because you're not passing a string as an argument but you're instead passing a function call that may not be returning a string. Make sure that the main function is returning an object of type string before passing it to the write function. You could opt to do this:

word = str(main())  #Ensuring a string is the main function returns a string
with open('INFO', 'a') as x:
    x.write(word)

Ensure that the main function has a return statement before passing it as an arguement.

  • Related