In: Computer Science
There are three steps (open, action, close) required for
handling files. You need to write a Python program what executes
each of these three steps. Your program must include:
Extensive comments to ensure explanation of your code (1).
Open a file (file name must include your student number, thus
filexxxxxxxx.txt). (1).
Write the details of the five students (from Question 1 above) to
a file (3).
Close the file. (1)
Then open the file again (1).
Write the contents of the file to display on the screen (3).
SOURCE CODE:
FileName=input("Enter the file name:") #reading filename from
user
file=open(FileName,'w') #opening file in write mode
n=int(input("Enter Number of students: ")) #reading Number of
students from user
Name=str()
IDNo=int()
Age=int() #initializing variable with default values
Grade=str()
temp_str="" #temp_str for file concatenation
print("Enter student Details to write into file:\n")
for i in range(n):
Name=input("Enter Name: ") #reading Name from user
IDNo=int(input("Enter IDNo: ")) #reading IDNo from user
Age=int(input("Enter Age: ")) #reading Age from user
Grade=input("Enter Grade: ") #reading Grade from user
#concatenating all variables data which is taken from user
temp_str=str(IDNo)+"\t"+Name+"\t"+str(Age)+"\t"+Grade+"\n"
file.write(temp_str) #writing concatenated string to file
file.close() #closing the file
print("Details of the students writed successfully")
print("\n")
file=open(FileName,'r') #Againing opening the file in
readmode
for record in file: #iterating over each line of file
print(record) #printing the record to console
file.close() #Closing the file
CODE
SCREENSHOT:
CONSOLE OUTPUT
file1234.txt