python - 如何在多个函数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
解决方案
您可以使用 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()
推荐阅读
- ios - 关闭应用程序时如何修复maccatalyst中的自定义方案打开?
- mysql - “字段列表”mysql存储过程中的未知列。如何解决这个问题?
- javascript - 通过多个分隔符拆分字符串并保留一些分隔符同时丢弃其他分隔符
- azure-devops - Azure DevOps - 动态评估需求名称
- javascript - 在Angular中组合没有重复的数组
- java - 构建主项目时如何自动构建子项目?
- excel - 使用 filedialog 选择并打开工作簿并立即在该新打开的工作簿中运行宏
- java - 警告:JPA 不支持自定义隔离级别,因此启动 Jobs 时可能不会获取锁
- kubernetes - 是否有可能在一个 aws 区域中创建主节点并在另一个区域中创建工作节点?
- javascript - 将 Express 请求传递给 Axios POST 请求