开发者

Raise of an eoferror for a file

 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 defi开发者_如何学运维ned


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)


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜