Raise of an eoferror for a file

我是研究僧i 提交于 2019-12-25 01:34:24

问题


 import pickle
filename=input('Enter a file name:')

def commands():
    f=open(filename,'w')
    names=[]
    grades=[]
    while True:
            name=input("Give a student's name:")
            if name.lower()=='end':
                    f.close()
                    print("File closed")
                    print("Back to Menu")
                    break
            else:
                    x=names.append(name)
                    f.write(str(x))
            grade=input("Give student's grade:")          
            try:
                grade=float(grade)
                if 0<=grade<=10:
                    y=grades.append(grade)
                    f.write(str(y))
                else:
                    print("Please give a grade!Between 0-10! ")
            except ValueError:
                print(grade,"is not a number...Give only Numbers!")




def syn2(filename):
    try:
        f=open(filename,'r')
        f.read(names)
        f.read(grades)
        d1={}
        d1[names]=grades
        print(d1)
        print("Back to Menu")
    except IOError:
        return False

WHEN I CALL syn2(filename) :

Traceback (most recent call last):
  File "file1.py", line 68, in 
  File "file2.py", line 45, in syn2
NameError: global name 'names' is not defined

回答1:


I would suggest keeping the students/grades in a dictionary. If the user has finished her input, pickle the dictionary into a file. Like

grades = {}
while True:
    # ask for student's name n
    # ...

    if n.lower() == 'end':
        break

    # ask for student's grade g
    # ...

    grades[n] = g

pickle.dump(grades, yourfile)



回答2:


You're running into the end of the file "EOF" before your program expects to.




回答3:


You have the error global name 'names' is not defined because you have declare names within def entoles() and is only seen within this scope.

You have to declare names outside the dev entoles() if you want to be able to access it.

Also

x=names.append(name)
f.write(str(x))

append is a method that append the item passed to the list in-place. The method returns 'None' Therefore, f.write(str(x)) will write 'None'.

EDIT: Python doc about Input/Output for f.read() and this Python doc for input/raw_input




回答4:


The problem is that the myfunc function reopens the file on each iteration, deleting its contents. You should move the open call to before the while loop.



来源:https://stackoverflow.com/questions/1876100/raise-of-an-eoferror-for-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!