python - Python初学者——使用常量打开文件回溯
问题描述
我试图开始在我的项目中使用常量,这发生了。
Traceback (most recent call last):
File "C:\Users\aletr\Desktop\Python projects\Restaurant software\r_0.py", line 39, in <module>
with constants.NAMES_R as f :
File "C:\Python30\lib\io.py", line 456, in __enter__
self._checkClosed()
File "C:\Python30\lib\io.py", line 450, in _checkClosed
if msg is None else msg)
ValueError: I/O operation on closed file.
我知道是因为文件被关闭了。但我不明白我是如何在没有常量的情况下使用相同的代码的,它会完美地工作。常数:
F_NAMES = 'names.txt'
NAMES_R = open(F_NAMES, 'r+')
NAMES_W = open(F_NAMES, 'w+')
脚本:
import constants
with constants.NAMES_R as f :
f_n = f.read().splitlines()
print("Welcome to NAME.app")
##############
# USER LOGIN #
##############
while True:
name = input("""
\n - Insert name to logg in
\n - ADD to save new user
\n - LIST to see saved users
\n - REMOVE to delete a user
\n - EXIT to finish
\n - ...""")
lname = name.lower()
if lname == "add":
n_input = input("Name:")
with open('names.txt', 'a') as f:
f.write(n_input + '\n')
elif lname == "list":
with constants.NAMES_R as f :
print(f.read().splitlines())
f.close()
elif name in f_n:
print("Logged as", name.upper())
user = name
input('Welcome, press enter to continue \n')
break
elif lname == 'remove':
remove = input("Insert user name to remove \n ...")
with constants.NAMES_R as f :
lines = f.readlines()
lines = [line for line in lines if remove not in line]
with constants.NAMES_W as f :
f.writelines(lines)
elif lname == "exit":
exit()
解决方案
推荐阅读
- python-3.x - 如何在 python 中计算 2、2D kde 图之间的公共体积/交集?
- javascript - 用户登录后如何打开侧边栏选项卡
- macos - cmake:如何在 macOS 上的应用程序包中找到二进制文件?
- django - Pinax npm 安装失败
- c# - C#:无法从 JSON 字符串中获取子值
- python - Odoo划分两个浮点字段 - AttributeError
- java - 在 Windows 上使用 JPackage 是否可以让 main .exe 不作为控制台运行,但让其他 laucher 作为控制台运行?
- c# - 以编程方式获取 Azure 应用服务本地磁盘使用情况
- azure - 令牌在 Blazor WebAssembly 中过期时无法捕获 CosmosException
- c++ - GCC/Clang 分歧:是否
匹配 在 C++17 模板模板替换中?