0% found this document useful (0 votes)
5 views

Reading a Specific Portion of a Text File python

CODE

Uploaded by

suyashverma115
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Reading a Specific Portion of a Text File python

CODE

Uploaded by

suyashverma115
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#Program 1: Reading a Specific Portion of a Text File python

def read_specific_portion(file_name, start, end):


with open(file_name, 'r') as file:
file.seek(start)
data = file.read(end - start)
return data

file_name = 'example.txt'
start_position = 10
end_position = 50

print("Content from position", start_position, "to", end_position, ":")


print(read_specific_portion(file_name, start_position, end_position))

#Program 2: Truncating a File at a Specified Position


python

def truncate_file_at_position(file_name, position):


with open(file_name, 'r+') as file:
file.seek(position)
file.truncate()

file_name = 'example.txt'
truncate_position = 20

truncate_file_at_position(file_name, truncate_position)
print("File truncated at position", truncate_position)

#Program 3: Reading and Writing Data to a File at a Specific Position


python

def read_write_at_position(file_name, position, data_to_write=None,


size_to_read=10):
with open(file_name, 'r+') as file:
file.seek(position)
if data_to_write:
file.write(data_to_write)
print("Data written at position", position)
else:
file.seek(position)
data = file.read(size_to_read)
print("Data read from position", position, ":", data)

file_name = 'example.txt'
write_position = 30
write_data = "New content"
read_position = 15

#read_write_at_position(file_name, write_position, write_data)


#read_write_at_position(file_name, read_position)
#These programs demonstrate practical applications of file handling operations in
Python, including reading specific portions of a file, truncating a file at a
certain position, and reading/writing data at specific positions within a file
using seek() and tell() methods.

#Below is a Python program that reads a text file and displays all the four-letter
words present in the file. Each step is explained with comments for better
understanding:python

def display_four_letter_words(file_name):
# Open the text file in read mode
with open(file_name, 'r') as file:
# Read the content of the file
content = file.read()
# Split the content into words based on whitespace
words = content.split()
print("Four-letter words in the file:")
# Iterate through each word
for word in words:
# Check if the length of the word is 4
if len(word) == 4:
# Print the four-letter word
print(word)

# File name of the text file


file_name = 'example.txt'
# Call the function to display four-letter words
display_four_letter_words(file_name)

You might also like