You are on page 1of 4

''' Q.

1
Write a Python program to open a
text file named "data.txt" in read
mode, use seek() to navigate to the
20th byte, read the next 100
characters, and display the content.
'''

f = open('data.txt', mode='r')
f.seek(20)
content = f.read(100)
print(content)
f.close()

''' Q.2
Differentiate between the return
type and usage of the methods
read(), readline() and readlines()
in Python.
'''
read():
Return Type: str
Usage: The read() method is used to read the entire contents of a file as a single string.
It reads from the current file position to the end of the file or up to the specified number of bytes,
if provided as an argument. If you don't specify the number of bytes to read, it will read the entire file.
Example:
with open('file.txt', 'r') as file:
data = file.read()

readline():
Return Type: str
Usage: The readline() method is used to read the next line from the file, starting from the current file position
It returns the content of the line as a string, including the newline character at the end.
If you call readline() multiple times, it will read subsequent lines one by one.
Example:
with open('file.txt', 'r') as file:
line1 = file.readline()
line2 = file.readline()

readlines():
Return Type: list of str
Usage: The readlines() method is used to read all the lines from the current file position to the end of the
and return them as a list of strings. Each string in the list represents a line from the file.
You can iterate through this list to access each line of the file.
Example:
with open('file.txt', 'r') as file:
lines = file.readlines()
for line in lines:
# Process each line

In summary, the key differences between these methods are in their return types and
how they read data from a file. read() returns the entire file content as a single string,
readline() reads one line at a time, and readlines() reads all lines and returns them as a list of strings.
The choice of method depends on your specific needs when working with files in Python.

***** IMPORTANT CONCEPTS TO UNDERSTAND BEFORE SOLVING Q.3 *****

To convert an integer to a byte stream and vice versa in Python,


you can use the int.to_bytes() method to convert an integer to bytes
and the int.from_bytes() method to convert bytes back to an integer.

Here's an example of how to do this:

Converting an integer to a byte stream:


integer_value = 42
byte_stream = integer_value.to_bytes(4) # Convert to a 4-byte byte stream
print(byte_stream)

In this example, we convert the integer 42 into a 4-byte byte stream in big-endian byte order.

Converting a byte stream back to an integer:


byte_stream = b'\x00\x00\x00\x2A' # Example byte stream (4 bytes)
integer_value = int.from_bytes(byte_stream)
print(integer_value)

In this example, we convert the 4-byte byte stream b'\x00\x00\x00\x2A' back to the integer value 42.

You can adjust the number of bytes and the byte order according to your specific requirements.

#just for reference


#to create a binary file: numbers.bin with numbers from 1-100:
f = open('numbers.bin', 'wb')
for i in range(1,100+1):
f.write(i.to_bytes(1))
print('File saved')
f.close()

'''Q.3
Write a Python program to read
integers from a binary file
"numbers.bin" and print them in
reverse order using seek() and
tell() to demonstrate the file
pointer's movement.
'''

f = open('numbers.bin', 'rb')
f.seek(-1,2)
file_pointer_position=f.tell()

i = 2
while file_pointer_position >= 0:
print(int.from_bytes(f.read(1)), end=" ")

if file_pointer_position == 0:
break

f.seek(-i,2)
file_pointer_position = f.tell()
i+=1

f.close()

''' Q.4
Write a Python program to create a
list of dictionaries, each
containing information about a
product, and save it as a binary
file named "products.pkl" using the
pickle module.
'''

import pickle

# Create a list of dictionaries containing product information


products = [
{"id": 1, "name": "Product A", "price": 19.99},
{"id": 2, "name": "Product B", "price": 29.99},
{"id": 3, "name": "Product C", "price": 39.99},
]

# Define the filename for the pickle file


file_name = "products.pkl"

# Save the list of dictionaries to a binary file using pickle


with open(file_name, 'wb') as file:
pickle.dump(products, file)

print(f"Products saved to {file_name}")

''' Q.5
Write a Python program to load and
display the content of the
"products.pkl" file created in
question 4. Perform data
manipulation on the loaded data,
such as sorting products based on
their prices in ascending order.
'''
import pickle

# Define the filename for the pickle file


file_name = "products.pkl"

# Load the list of products from the binary file using pickle
with open(file_name, 'rb') as file:
products = pickle.load(file)

# Display the loaded product information


print("Products loaded from 'products.pkl':")
for product in products:
print(f"Product ID: {product['id']}, Name: {product['name']}, Price: {product['price']}")

# Sort the products based on their prices in ascending order


sorted_products = sorted(products, key=lambda x: x['price'])

# Display the sorted products


print("\nSorted products by price (ascending order):")
for product in sorted_products:
print(f"Product ID: {product['id']}, Name: {product['name']}, Price: {product['price']}")

''' Q.6
Write a Python program to analyze a
text file named "info.txt" and
display the following information:
-Total number of characters
-Total number of words
-Total number of lines
'''
file_name = "data.txt"

# Initialize counters for characters, words, and lines


char_count = 0
word_count = 0
line_count = 0

# Open and read the file


with open(file_name, 'r') as file:
for line in file:
# Update line count
line_count += 1

# Update character count by adding the length of the line


char_count += len(line)

# Split the line into words and update word count


words = line.split()
word_count += len(words)

# Display the information


print("Total number of characters:", char_count)
print("Total number of words:", word_count)
print("Total number of lines:", line_count)

''' Q.6
Write a function count_Dwords() in
Python to count the words
ending with a digit in a text file
"Details.txt".
Example:
If the file content is as follows:
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Output will be:
Number of words ending with a digit
are: 4
'''
f = open('Details.txt', 'r')
Digit_ended_word_count = 0

text_file_content = f.read().split()

for a_word in text_file_content:


if a_word[-1].isdigit():
Digit_ended_word_count += 1

print(Digit_ended_word_count)

'''Q.8
Explain the purpose and
functionality of the Python pickle
module in binary file handling,
including its support for complex
data structures.
'''

'''
The Python `pickle` module is used for binary file handling and provides a way to serialize
and deserialize Python objects. It allows you to save Python objects to binary files and
load them back into memory, preserving their data structures. T

he primary purposes and functionalities of the `pickle` module are as follows:


1. Serialization:
- The primary purpose of the `pickle` module is to serialize Python objects,
which means converting complex data structures, such as lists, dictionaries, classes,
and user-defined objects, into a binary representation that can be stored in a file.
2. Persistence:
- `pickle` is commonly used to save the state of Python objects to disk.
This is useful when you want to save the current state of your program,
including data and data structures, so you can resume working with them later
without having to recreate the objects from scratch.

3. Cross-Version Compatibility:
- Pickle files can be used to transfer data between different versions of Python,
as the module handles the details of data representation and Python version compatibility.

4. Support for Complex Data Structures:


- `pickle` can serialize and deserialize a wide range of Python objects, including:
- Simple data types (integers, floats, strings, etc.)
- Compound data types (lists, dictionaries, sets, etc.)
- Custom objects and classes
- Functions and lambdas
- Nested data structures (e.g., lists of dictionaries)
- Circular references (references between objects, which are preserved during pickling)

Here's a basic example of using the `pickle` module to serialize and deserialize a Python object:
'''

import pickle

# Data to be serialized
data = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'}

# Serialize (save) the data to a binary file


with open('data.pkl', 'wb') as file:
pickle.dump(data, file)

# Deserialize (load) the data from the binary file


with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)

print(loaded_data) # Output: {'name': 'Alice', 'age': 30, 'city': 'Wonderland'}

'''
In this example, we use `pickle.dump()` to save the `data` dictionary to a binary file,
and then we use `pickle.load()` to load it back into memory.
The loaded data is an exact copy of the original dictionary,
preserving its data structure and contents.

While the `pickle` module is powerful and convenient,


it's important to note that pickle files can be a security risk if used
with untrusted data sources since they can execute arbitrary code during deserialization.
Always be cautious when using pickle files, and avoid loading them from untrusted or unauthenticated sources.
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js

You might also like