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

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XII - CSV FILE

CSV FILE (COMMA SEPERATED VALUE) CSV NOTES LINK :  CSV NOTES - CLICK HERE Writing data to a CSV file involves the following steps: Import the csv module Open the CSV file in write mode ( "w" ) using open() Create the writer object Write the data into the file using the writer object Close the file using close() writerow() Method This method is used to write a single row to a CSV file. It takes a sequence (list or tuple) as its parameter, and writes the items as a comma-separated line in the file. You do not need to add a newline character (\n) — it automatically places the end-of-line marker.     EXAMPLE 1: import csv  # Importing the csv module # CSV file opened using relative path csv_fobj = open("emp.csv", "w")   # Writer object created wtr_obj = csv.writer(csv_fobj) # Record with field heading is written wtr_obj.writerow(["Empno", "Name", "Salary"]) # Records with data are...