Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

Python beginner - using constant to open file traceback

I'm trying to start using constants in my project and this happened.

Traceback (most recent call last):
  File "C:UsersaletrDesktopPython projectsRestaurant software
_0.py", line 39, in <module>
    with constants.NAMES_R as f :
  File "C:Python30libio.py", line 456, in __enter__
    self._checkClosed()
  File "C:Python30libio.py", line 450, in _checkClosed
    if msg is None else msg)
ValueError: I/O operation on closed file.

I know is because the file it's been closed. But I don't understand how I was using the same code without constant and it would work perfectly. constants:

F_NAMES = 'names.txt'
NAMES_R = open(F_NAMES, 'r+')
NAMES_W = open(F_NAMES, 'w+')

script:

import constants
with constants.NAMES_R as f :
    f_n = f.read().splitlines()
print("Welcome to NAME.app")
##############
# USER LOGIN #
##############
while True:
    name = input("""
    
 - Insert name to logg in
    
 - ADD to save new user
    
 - LIST to see saved users
    
 - REMOVE to delete a user
    
 - EXIT to finish
    
 - ...""")

    lname = name.lower()

    if lname == "add":
        n_input = input("Name:")
        with open('names.txt', 'a') as f:
            f.write(n_input + '
')

    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 
')
        break

    elif lname == 'remove':
        remove = input("Insert user name to remove 
 ...")
        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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...