Python file object, file seek and tell methods
Display the file name, mode
file=open("test1.txt","r")
print(file.name,file.mode,file.closed)
file.close()
Output
Reading every line from the file test1
file=open("test1.txt","r")
for line in file:
print(line[:-1])
file.close()
Output
Exercise - Reading every line from the file and displaying student name and faculty name alone
file=open("test1.txt","r")
for line in file:
k=line.split(",")
print("The student name is ",k[1])
print("The faculty name is ",k[3])
file.close()
Output
Read and display only students who have faculty members with doctorate degrees
first 9 characters is reg number
next six characters is name
next 7 characters is location
next 10 characters is faculty name
Output
Read BIT from the file
file=open("test2.txt","r")
file.seek(35,0)
k=file.readline(3)
file.close()
print(k)
Output
Tell where the cursor is after the read
file=open("test2.txt","r")
file.seek(35,0)
k=file.readline(3)
print(file.tell())
file.close()
print(k)
Output
Seeking the faculty name using 1
file=open("test2.txt","br")
file.seek(35,0)
k=file.readline(3)
print(k)
print(file.tell())
file.seek(16,1)
facultyname=file.read(10)
print(facultyname)
file.close()
seeking from the end of the file
file=open("test2.txt","br")
file.seek(-10,2)
k=file.read()
print(k)
file.close()
Output
Seeking in the reverse direction from the current location
file=open("test2.txt","br")
file.seek(2,0)
k=file.read(3)
print(k)
file.seek(-3,1)
k=file.read(3)
print(k)
file.close()
Output