Python File Programs



Write a program to create a text file of students to store Roll No., Name and three subject marks obtained by the students in a class of 15 students.

Program:

student=open("marks.txt",'w')

for i in range(3):

record=""

r=input("Enter Roll No. :")

record=record+r+"\n"

nm=input("Enter Name:")

record=record+nm+"\n"

m1=input("Enter Marks1 :")

record=record+m1+"\n"

m2=input("Enter Marks 2:")

record=record+m2+"\n"

m3=input("Enter Marks 3:")

record=record+m3+"\n"

student.write(record)

student.close()


Write a program to add details of two more student into the text file 'marks.txt' which is already created on the disk.

Program:

student=open('marks.txt', 'a')

for i in range (2):

record=""

r=input("Enter Roll No. :")

record=record+r+"\n"

nm=input("Enter Name: ")

record=record+nm+"\n"

m1=input("Enter Marks 1: ")

record=record+m1+"\n"

m2=input("Enter Marks 2:")

record=record+m2+"\n"

m3=input("Enter Marks 3: ")

record=record+m3+"\n"

student.write(record)

student.close()

Output:

Enter Roll No. :101

Enter Name: Raj

Enter Marks 1: 89

Enter Marks 2:90

Enter Marks 3: 78

Enter Roll No. :102

Enter Name: Rita

Enter Marks 1: 89

Enter Marks 2:67

Enter Marks 3: 78


Write a python program to read a random line from a file

Program:

import random


def random_line(afile):

line = next(afile)

for num, aline in enumerate(afile, 2):

if random.randrange(num):

continue

line = aline

return line



11 views1 comment

Recent Posts

See All

Python program to add one or more element in List

Program: #Append() is used for adding one element in List at the end of list. X=[9,18,27] X.append(36) print(X) output: [9, 18, 27, 36] #Insert () is used for add element at any given position in the

Python program to remove elements of a given list

Program: n=[9,18,27,36,45,54,63] print("List=",n) i=int(input("Enter the position of elements to delete : ")) del n[i] print("List after deletion=",n) del n[:2] print("List after deleting first two el

Python program to create a list of 5 numbers

Python program to create a list of 5 numbers. Numbers entered by User. n=[] for i in range(5): j=int(input("Enter number: ")) n.append(j) print("The List is", n) Output: Enter number: 3 Enter number: