Skip to main content

GRADE XII - CS - TEXT FILES

 

Random Access in File

All the file manipulation functions discussed till now are used to access the data sequentially from a file i.e from beginning.

When it is required to access data in a random fashion from any position, the seek() and tell() functions of Python are used.

The seek() and tell() methods are used to manipulate the file pointer of a file.

A file pointer is logical marker which keeps track of the number of bytes read or written in a file.

       When the file is opened in the read mode (“r”), the file pointer is positioned at 0th byte and the pointer automatically moves after every read or write operation.

       Similarily, when the file is opened in append mode, it is positioned at the end of file.

       The file operation starts from the position of the file handle

 

Random Access in File - seek() Method

seek() method is used to change the position of the File Handle to a given specific position.

Syntax :          file_object.seek(offset, [reference_point])

       offset - no. of bytes (integer) by which the file object is to be moved.

       reference_point - indicates the starting position of the file object from

which the file handle will move.

The reference point can have any of the following values:

1      -           beginning of the file

2      -           current position of the file

3      -           end of file

The reference point refers to the position from which the offset has to be counted i.e Offset is added to reference point to position the file handle.

The reference point is optional in seek(). When not given, by default, the value of reference_point is taken as 0, i.e. the offset is counted from the beginning of the file.

Note :  The values of reference point 1 and 2 work only, if the file has been opened for binary mode

EG:

#Use of seek()

file = open("text.txt","w")

file.write("This program is creating a text file\n")

file.close()

file = open("text.txt","r")

file.seek(8) #file pointer positioned at 8th byte –(g of program)

str= file.read(4) # 4 characters read from current position (gram)

print(str) #Display gram

file.seek(5)  #file pointer positioned at 5th byte (on p of program)

print(file.read()) #file read from 5th position till end of file

file.seek(0) #file pointer positioned at beginning

print(file.read(12)) # 12 characters read from 0th byte

file.close()

OUTPUT:

gram

This program

 

EG:

with open("Test.txt",'w') as F:

    F.write("abcdefghi\n")

with open("Test.txt",'r') as F:

    for i in range(4):

    F.seek(i)

    print(F.read(i+1))


Random Access in File -tell() Method

The tell() method returns an integer giving the current position of file object in the file.

The integer returned specifies the number of bytes from the beginning of the file till the current position of file object.

Syntax:fileobject.tell()

Example:fin = open("text.txt","r")

print(fin.tell())

Output:0

When the file is opened in the reading mode, the file handle is positioned in the 0thbyte i.ethe beginning of the file. Hence, the output is 0

Similarly, when the file is opened in append mode, the file handle is positioned at the end of the file. Hence the statement print(fin.tell()) can be used to display the size of the file.

Random Access in File -tell() Method

file = open("sample.txt", "w+")  #w+ Opens the file for both writing and reading

file.write("Hello World")

print("Current position:", file.tell())  # After writing

 

file.seek(0)  # Move to beginning

print("Position after seek(0):", file.tell())

 

data = file.read(5)  # Read 5 characters

print("Data Read:", data)

print("Position after reading 5 characters:", file.tell())

 

file.close()

 

Meaning of "w+" Mode:

  • Opens the file for both writing and reading.
  • Creates the file if it does not exist.
  • Overwrites the file (deletes all existing content) if it already exists.
  • The file pointer is placed at the beginning of the file.

 # Open file in w+ mode (write + read)

f = open("sample.txt", "w+")

# Write to the file

f.write("Hello World\n")

f.write("Welcome to Python")


# Move pointer back to the beginning

f.seek(0)


# Read the contents

content = f.read()

print("File content:\n", content)


f.close()

#Without seek(0), the read() would print nothing, because the pointer would be at the end of the file after writing.

Eg:

f = open("file.txt", "w+")

f.write("Example text")

print(f.read())  # ❌ Will print nothing — pointer is at end

Correct Code:

f.seek(0)

print(f.read())



r+ Mode in Python File Handling: 

The r+ mode is used to open a file for both reading and writing.

·       The file must already exist. If it does not, Python will raise a FileNotFoundError.

·       The file pointer is placed at the beginning of the file.

·       You can read from and write to the file.

·       When you write, it overwrites the content from the current file pointer onward (it doesn't insert).

EG:

f1=open("text.txt","r+") 

print(f1.read()) 

str=input("Enter string:") 

f1.write(str+'\n') 


f1.seek(2)

print("The new content") 

print(f1.read()) 

f1.close() 


·       When you write, it overwrites the content from the current file pointer onward (it doesn't insert).

"r"

Read only (default)

"w"

Write only (overwrites file)

"a"

Append only

"r+"

Read + Write (doesn't delete content)

"w+"

Write + Read (deletes content)

"a+"

Append + Read (keeps content, adds to end)

 


Comments

Popular posts from this blog

PYTHON - MYSQL CONNECTIVITY CODE

  #INSERTION OF DATA import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="root", database="school" ) print("Successfully Connected") #print(mydb) mycursor=mydb.cursor()   v1=int(input("enter ID:")) v2=input("enter name:") v3=input("enter Gender:") v4=int(input("enter age:")) sql='insert into TEACH values("%d","%s","%s","%s")'%(v1,v2,v3,v4) print(sql) mycursor.execute(sql) mydb.commit() print("record added") #MYSQL Connection code – Deletion on database SOURCE CODE: s=int(input("enter id of TEACHER to be deleted:")) r=(s,) v="delete from TEACH where id=%s" mycursor.execute(v,r) mydb.commit() print("record deleted") MYSQL Connection code – Updation on database SOURCE CODE: import mysql.connector mydb = mysql.connector.c...

GRADE XII CS - VIVA QUESTIONS

  VIVA QUESTIONS GRADE XII CS Dear All Be thorough with your project and practical files, as the viva can be asked from anywhere. Stay calm, don’t get nervous, and be confident in front of the examiner. 1. Tell me about your project. 2. Which concepts you have used for your project? 3. What do you mean by front end and back end? How they are important in developing any such projects? 4  Mention the modules and built-in functions you have used in your project. 5. Which real world problems are solved by your project? 6. Explain the most important feature of your project. 7. Name a few mutable data types of python. Lists, Sets, and Dictionaries 8. Name a few immutable data types of python. Strings, Tuples, Numeric 9. Name ordered and unordered data type of python. Ordered – String, List, Tuples Unordred – Set, Dictionaries 10. What is the significance of a pass statement in python? pass is no operation python statement. This is used where python requires syntax but logic requires...