Introduction :
Welcome back to my Python journey! Yesterday, I laid the foundation with file handling.
Today, I dove into something more on file handling, essential for any programming language. Let’s explore what I learned!
File Handling :
Reading Character Data from text files: –
We can read character data from text file by using the following read methods.
read() -> To read total data from the file read(n) -> To read ‘n’ characters from the file (n number of char) readline() -> To read only one line readlines() -> To read all lines into a list Eg 1: To read total data from the file
fname = input (“enter file name”) f=open(fname,’r’) data=f.read()
print(data)
f.close()
Eg 2:
To read only first 10 characters:
fname = input (“enter file name”) f=open(fname,’r’) data=f.read(10)
print(data)
f.close()
Eg 3:
To read data line by line: fname = input (“enter file name”) f=open(fname,’r’)
line1=f.readline()
print(line1,end=”)
line2=f.readline()
print(line2,end=”)
line3=f.readline()
print(line3,end=”)
f.close()
Eg 4:
To read all lines into list: fname = input (“enter file name”) f=open(fname,’r’)
lines=f.readlines()
for line in lines:
print(line,end=”)
f.close()
The with statement: –
The with statement can be used while opening a file.
We can use this to group file operation statements within a block.
The advantage of with statement is it will take care closing of file,after completing all operations automatically even in the case of exceptions also, and we are not required to close explicitly.
Eg :
with open(“abc.txt”,”w”) as f: f.write(“jithon\n”) f.write(“python\n”) f.write(“program\n”) print(“Is File Closed: “,f.closed) #False print(“Is File Closed: “,f.closed) #True
The seek() and tell() methods: –
We can use tell() method to return current position of the cursor(file pointer) from beginning of the file.
The position(index) of first character in files is zero just like string index.
Eg :
f=open(“lit.txt”,”r”) print(f.tell()) print(f.read(2)) print(f.tell()) print(f.read(3)) print(f.tell()) print (f.close)
We can use seek() method to move cursor(file pointer) to specified location Synatx : f.seek(offset, fromwhere) ata =”Hello Python is Easy!” f= open (“lit.txt”, “w”) f.write (data) with open (“lit.txt”, “r+”) as f : text = f. read() print (text, “current cursor position:”,f.tell ()) f.seek (15) print (“current cursor position:”,f.tell ()) f.write (“jithon”) f.seek (6) text = f.read () print (“after modify”) print (text)
#Program to print the number of lines,words and characters present in the given file? import os,sys fname=input(“Enter File Name: “) if os.path.isfile(fname): print(“File exists:”,fname) f=open(fname,”r”) else: print(“File does not exist:”,fname) sys.exit(0) lcount=wcount=ccount=0 for line in f: lcount=lcount+1 ccount=ccount+len(line) words=line.split() wcount=wcount+len(words) print(“The number of Lines:”,lcount) print(“The number of Words:”,wcount) print(“The number of Characters:”,ccount)