这是我的密码:
fh = open('students.txt', 'r')
def dictio_maker(direc):
count = 0
for line in fh:
line = line.split(" ") #Separates each string in each line
student_num = line[0] #Sets the first element of the list "line" as the student_num
student_name = line[1] #Sets the second element of the list "line" as the student_name
student_grade = line[2] #Sets the third element of the list "line" as the student_grade
count =+ 1 #To change the key names
direc[student_num] = [student_name,student_grade]
student_num = "student_num" + str(count) #Changes the key names for the next iteration
student_grade = "student_grade" + str(count)
student_name = "student_name" + str(count)
print(direc)
return direc
def append(direc):
x = input('Do you want to modify an entry? (yes/no)')
if x == "yes":
while True:
try:
student_num = int(input('Enter student num: '))
except ValueError:
print('Please enter a valid input')
continue
break
if student_num in direc.keys():
print('Already existing. Please enter another.')
else:
fh.write(str(student_num) + " ")
while True:
try:
student_name = input('Enter student name: ' )
except ValueError:
print('Please enter a valid input')
continue
break
fh.write(str(student_name) + " ")
while True:
try:
student_grade= float(int(input('Enter student grade: ')))
except ValueError:
print('Please enter a valid input')
continue
break
fh.write(str(student_grade) + " " + '\n')
dictio_maker(direc)
print(direc)
else:
fh.close()
def main():
direc= {}
dictio_maker(direc)
append(direc)
if __name__ == '__main__':
main()
它的功能: 最初,我有一个文本文件,其中包含此程序所需的输入,格式如下:
student_num1 student_name1 student_grade1
student_num2 student_name2 student_grade2
student_num3 student_name3 student_grade3
第一个函数基本上是将输入txt文件中的文本行转换为字典“direc”中的输入
我想做的是: 现在,我要为下一个函数做的是询问用户是否要添加另一个条目。如果是,我要求用户输入学号,如果学号不存在,则接受name和grade的新值并将其添加到文本文件(students.txt)中。但是如果学生号存在,请再次要求用户输入另一个条目(学生号)
问题是: 我得到一个错误:
File "C:/Users/Dust/Desktop/alemios_students_add.py", line 35, in append
fh.write(str(student_num) + " ")
UnsupportedOperation: not writable
我也不确定我所做的代码是否能正常工作
您的文件处于只读模式:
您需要将其更改为:
警告:此解决方案覆盖文件中的现有数据
相关问题 更多 >
编程相关推荐