The with Statement

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:

#Follow - Programmerfect

with open("abc.txt","w") as f:
    f.write("Programmerfect\n")
    f.write("Richard\n")
    f.write("Rahul\n")
    print("Is File Closed: ",f.closed)
print("Is File Closed: ",f.closed)

Output:

The seek() and tell() methods: 

tell():

  • We can use tell() method to return current position of the cursor(file pointer) from beginning of the file. [ can you please tell current cursor position]. 
  • The position(index) of first character in files is zero just like string index.
  • The tell() method returns the current file position in a file stream.

Syntax

  • file.tell()  

Parameter Values

  • No parameter values.

Eg:

#Follow - Programmerfect

f=open("abc.txt","r")
print(f.tell())
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())

seek():  

  • We can use seek() method to move cursor(file pointer) to specified location. [Can you please seek the cursor to a particular location] 
  • The seek() method sets the current file position in a file stream.
  • The seek() method also returns the new position.

Syntax

  • file.seek(offset)
  • file.seek(offset, fromwhere)
offset represents the number of positions
The allowed values for second attribute(from where) are 
  • 0---->From beginning of file(default value) 
  • 1---->From current position 
  • 2--->From end of the file
Note: Python 2 supports all 3 values but Python 3 supports only zero. 

Parameter Values

  • offset - A number representing the position to set the current file stream position.

Eg:

#Follow - Programmerfect

data="All Students are STUPIDS"
f=open("abc.txt","w")
f.write(data)
with open("abc.txt","r+") as f:
    text=f.read()
    print(text)
    print("The Current Cursor Position: ",f.tell())
    f.seek(17)
    print("The Current Cursor Position: ",f.tell())
    f.write("PROGRAMMER!!!")
    f.seek(0)
    text=f.read()
    print("Data After Modification:")
    print(text)    


 

 






















Comments