python - calling a second function within another function -
i open file using a_reader function. use second function print file. want because able call open file function later without printing it. ideas on best way this? here sample code know not work may explain want do
def main (): a_reader = open ('c:\users\filexxx.csv','r') filename = a_reader.read() a_reader.close() def print(): print filename main() print()
please see day old thread: what pythonic way avoid reference before assignment errors in enclosing scopes?
the user in post had exact same issue, wanted define function within function (in case main
) adviced both me , others don't nest functions!
there's no need use nested functions in python, adds useless complexity doesn't give real practical advantages.
i do:
def main (): a_reader = open ('c:\\users\\filexxx.csv','r') filename = a_reader.read() a_reader.close() return filename print(main())
or
class main(): def __init__(self): a_reader = open ('c:\\users\\filexxx.csv','r') self.filename = a_reader.read() a_reader.close() def _print(self): print(self.filename) = main() a._print()
it's never idea define function-/class-names same default python functions/classes. print
being 1 of them.
but here's solution if wanna go original setup:
def main (): a_reader = open ('c:\\users\\filexxx.csv','r') filename = a_reader.read() a_reader.close() def _print(): print filename _print() main()
oh, , btw.. strings backslashes should escaped or need use r'..'
:)
Comments
Post a Comment