本文介绍了引发文件错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
当我致电syn2(filename)时:
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
推荐答案
您有错误global name 'names' is not defined
,因为您在def entoles()
中声明了names
并且仅在此范围内可见.
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.
如果要访问它,必须在dev entoles()
之外声明names
.
You have to declare names
outside the dev entoles()
if you want to be able to access it.
也
x=names.append(name)
f.write(str(x))
append是一种将传递的项目就地附加到列表的方法.该方法返回无"因此,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'.
有关f.read()和此Python文档用于输入/原始输入
这篇关于引发文件错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!