[英]Writing File and Reading from File in python
import random
class Student:
#easy way or short way to printing student details
def student_details(self):
print("Student number :",self.student_number)
print("-----------")
print("First Name : ",self._firstname)
print("-----------")
print("Last Name : ",self._lastname)
print("-----------")
print("Date Of Birth : ",self._date_of_birth)
print("-----------")
print("Gender : ",self._sex )
print("-----------")
print("Country of birth : ",self._country)
#constructor for the class and assign the variables(eg:firstname)
def __init__(self,firstname,lastname,date_of_birth,sex,country):
self.student_number = random.randint(1,18330751)
self._firstname = firstname
self._lastname = lastname
self._date_of_birth = date_of_birth
self._sex = sex
self._country = country
def get_firstname(self):
return self._firstname
def set_firstname(self,firstname):
self._firstname = firstname
def get_lastname(self):
return self._lastname
def set_lastname(self,lastname):
self._lastname = lastname
def get_date_of_birth(self):
return self._date_of_birth
def set_date_of_birth(self,date_of_birth):
self._date_of_birth = date_of_birth
def get_sex(self):
return self._sex
def set_sex(self,sex):
self._sex = sex
def get_country(self):
return self._country
def set_country(self,country):
self._country = country
#this method for converting object when writing to file and reading the file
def __str__(self):
return f"{firstname,lastname,date_of_birth,sex,country}"
student = []
while True:
print("1. Enter 1 and you are going Write the contents of the student array to a file")
print("-----------")
print("2.Read student data from a file and populate the student array.")
print("-----------")
print("3.Add a new student")
print("-----------")
print("4. Enter 4 and you are going to see all students information")
print("-----------")
print("5. Enter 5 and you are going to write born year to find students who born in this year")
print("-----------")
print("6. Enter 6 and you are going to modify a student record by typing student number because you can't change student number")
print("-----------")
print("7. Enter 7 and you are going to write student number to delete student")
print("-----------")
print("8. Enter 8 and exit the program")
print("-----------")
print("You can choose what to do")
option = int(input("Please write your option: "))
print("-----------")
if option == 1:
f = open("cmse318.txt","w")
for data in student:
f.write(data)
print("-----------")
print("Successfully write to a file!!")
print("-----------")
break
f.close()
if option == 2:
f = open("cmse318.txt","r")
for ln in f:
firstname,lastname,date_of_birth,sex,country = ln.split(",")
s = Student(firstname,lastname,date_of_birth,sex,country)
student.append(s)
print(s)
f.close()
if option == 3:
firstname,lastname,date_of_birth,sex,country = map(str,input("Please Enter student details like this(cemal,göymen,2000,male,cyprus) : ").split(","))
s = Student(firstname,lastname,date_of_birth,sex,country)
student.append(s)
print("-----------")
print('Student created successfully!!')
print("-----------")
print("-----------")
if option == 4 :
for st in student:
st.student_details()
print("-----------")
print("For now these are the students")
print("-----------")
if option == 5:
year1 = int(input("Enter year to show students who born in this year(eg:2000): "))
for dob in student:
if (int(dob.get_date_of_birth()) == year1):
dob.student_details()
print("-----------")
print("All students who born in ", year1)
print("-----------")
if option == 6:
snr = int(input("Enter a student number: "))
for sn in student:
if sn.student_number == snr:
firstname,lastname,date_of_birth,sex,country = map(str,input("Please Enter student details like this(cemal,göymen,2000,male,cyprus) :").split(","))
sn.set_firstname(firstname)
sn.set_lastname(lastname)
sn.set_date_of_birth(date_of_birth)
sn.set_sex(sex)
sn.set_country(country)
print("-----------")
print("Student modify success")
print("-----------")
if option == 7:
snr = int(input("Enter the student number to be deleted : "))
for sn in student:
if sn.student_number == snr:
temp = sn
student.remove(temp)
print("-----------")
print("Student deleted successfully")
print("-----------")
if option == 8:
break
I need help in option 1 and option 2 about reading and writing file.我需要有关读取和写入文件的选项 1 和选项 2 的帮助。 In the reading file it does not read all students from a file it reads just one student and ıf there is more than one student in the file it gives an error.
在阅读文件中,它不会从一个文件中读取所有学生,它只读取一个学生,如果文件中有多个学生,则会出错。 In the writing to file part, the problem is I cannot write the student array to file it just write the last element from the student array but I need all elements from my student array.
在写入文件部分,问题是我无法将学生数组写入文件,它只写入学生数组中的最后一个元素,但我需要学生数组中的所有元素。
Code can be improved as follows.代码可以改进如下。
import random
class Student:
def __init__(self,firstname,lastname,date_of_birth,sex,country,student_number = None):
# reuse student number when we read from file (i.e. if specified)
# set new one if we don't have one
self.student_number = student_number or random.randint(1,18330751) # or causes use of rand value
# if student_number = None
self._firstname = firstname
self._lastname = lastname
self._date_of_birth = date_of_birth
self._sex = sex
self._country = country
def student_details(self):
return (f"Student number : {self.get_student_number()}\n"
f"----------- First Name : {self.get_firstname()}\n"
f"----------- Last Name : {self.get_lastname()}\n"
f"----------- Date Of Birth : {self.get_date_of_birth()}\n"
f"----------- Gender : {self.get_sex()}\n"
f"----------- Country of birth : {self.get_country()}")
def get_firstname(self):
return self._firstname
def set_firstname(self,firstname):
self._firstname = firstname
def get_lastname(self):
return self._lastname
def set_lastname(self,lastname):
self._lastname = lastname
def get_date_of_birth(self):
return self._date_of_birth
def set_date_of_birth(self,date_of_birth):
self._date_of_birth = date_of_birth
def get_sex(self):
return self._sex
def set_sex(self,sex):
self._sex = sex
def get_country(self):
return self._country
def set_country(self,country):
self._country = country
def get_student_number(self):
return self.student_number
def __str__(self):
' For serializing attributes to string --useful for writing to file '
return (f"{self.get_student_number()},"
f"{self.get_firstname()},"
f"{self.get_lastname()},"
f"{self.get_date_of_birth()},"
f"{self.get_sex()},"
f"{self.get_country()}")
def get_student_info():
' Use helper function to ensure student entry has correct number of fields '
while True:
while True:
entry = input('''Please Enter student details comma delimited like this (firstname,lastname,date of birth,gender,country)
Example Emal,Göymen,4/15/2000,Male,Cyprus : ''')
fields = entry.split(',')
if len(fields) == 5:
# Correct number of fields
return fields
else:
print(f'Entry {entry} incorrecst format')
print('Shoulbe be five comma delimitede fields i.e. firstname,lastname,date of birth,gender,country')
students = []
while True:
print('''
1. Write the contents of the student array to a file
-----------
2. Read student data from a file and populate the student array.
-----------
3. Add a new student
-----------
4. Display all students information
-----------
5. Information for students born in a particular year
-----------
6. Modify student record (you need to know student number)
-----------
7. Delete a student (you need to know student number)
-----------
8. Exit program
-----------
Enter option''')
option = int(input("Please write your option: "))
print("-----------")
if option == 1:
with open("cmse318.txt", "w") as f:
for st in students:
f.write(str(st) + '\n')
print("-----------\nSuccessfully wrote to a file!!\n-----------")
if option == 2:
with open("cmse318.txt","r") as f:
students = [] # Start new student array
for ln in f:
student_number,firstname,lastname,date_of_birth,sex,country = ln.rstrip().split(",") # rstrip remove '\n' at end of line
student_number = int(student_number)
s = Student(firstname,lastname,date_of_birth,sex,country,student_number)
students.append(s)
print(str(s))
if option == 3:
firstname,lastname,date_of_birth,sex,country = get_student_info()
s = Student(firstname,lastname,date_of_birth,sex,country)
students.append(s)
print('''-----------
Student created successfully!!
-----------
-----------''')
if option == 4 :
print('''-----------
For now these are the students
-----------
-----------''')
for st in students:
print(st.student_details())
if option == 5:
birth_year = input("Enter year to show students who born in this year(eg:2000): ")
print("-----------"
f"All students who born in {birth_year}"
"-----------")
for st in students:
if birth_year in st.get_date_of_birth(): # e.g. birth_year = 2000, date_of_birth = "May 5, 2000" we get a match
print(st.student_details())
if option == 6:
snr = int(input("Enter a student number: "))
for sn in students:
if sn.student_number == snr:
firstname,lastname,date_of_birth,sex,country = get_student_info()
sn.set_firstname(firstname)
sn.set_lastname(lastname)
sn.set_date_of_birth(date_of_birth)
sn.set_sex(sex)
sn.set_country(country)
print("-----------\nStudent modify success\n-----------")
break
else:
print(f"Student number {snr} not found!!!")
if option == 7:
snr = int(input("Enter the student number to be deleted : "))
# Normally bad practice to delete elements in list while iterating over it,
# but in this case we are only deleting a single element so okay
for sn in students:
if sn.student_number == snr:
students.remove(sn)
print(f"-----------\nStudent {snr} deleted successfully")
break
else:
print("Student {snr} not found")
if option == 8:
print('Exiting')
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.