How to keep open a file in mutiple functions python

Viewed 104

Hey I would like to know how do I keep open : open(namefile + ".py", 'w') in multiple fonctions , like :

invalid_inputCHOICE = True
invalid_inputCHOICE2 = True


def start():
    invalid_inputCHOICE = False
    print('creating file')
    with open("Hello World.txt", 'w') as f:
        f.write('Hello\n')
        world()



def world():
    invalid_inputCHOICE2 = False
    Answer = input('Should I write World ?')
    if Answer == 'yes':
        f.write('world')
    if Answer == 'no':
        print('Okay')
    else:
        print('please enter yes or no')
        world()

while invalid_inputCHOICE:
    start()
while invalid_inputCHOICE2:
    world()

and I got error : f is not defined but I defined it up . So how can I do to fix this but keep my functions ? error logs :

Traceback (most recent call last):
  File "H:/PYTHON-WORKSPACE/FileCreations.py", line 26, in <module>
    start()
  File "H:/PYTHON-WORKSPACE/FileCreations.py", line 10, in start
    world()
  File "H:/PYTHON-WORKSPACE/FileCreations.py", line 23, in world
    world()
  File "H:/PYTHON-WORKSPACE/FileCreations.py", line 18, in world
    f.write('world')
NameError: name 'f' is not defined
1 Answers

You can use the global keyword to make the scope of the f variable global :

invalid_inputCHOICE = True
invalid_inputCHOICE2 = True

with open("Hello World.txt", 'w') as f:
    f.write('Hello\n')

def start():
    global f    # making the scope of the f varible global
    invalid_inputCHOICE = False
    print('creating file')
    world()

def world():
    global f    # making the scope of the f varible global
    invalid_inputCHOICE2 = False
    Answer = input('Should I write World ?')
    if Answer == 'yes':
        f.write('world')
    if Answer == 'no':
        print('Okay')
    else:
        print('please enter yes or no')
        world()

while invalid_inputCHOICE:
    start()
while invalid_inputCHOICE2:
    world()
Related