首页 > 解决方案 > 如何在多个函数python中保持打开文件

问题描述

嘿,我想知道如何保持开放: open(namefile + ".py", 'w')在多种功能中,例如:

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()

我得到了错误: f 没有定义,但我定义了它。那么我该如何解决这个问题但保留我的功能呢?错误日志:

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

标签: python

解决方案


您可以使用 global 关键字来使 f 变量的范围为 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()

推荐阅读