首页 > 解决方案 > 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()

标签: pythonpython-3.x

解决方案


推荐阅读