I want to read the following text from .txt file
Title : Linux System Programming Talking Directly to the Kernel and C Library
Publisher : O'Reilly Media
Edition : 2
Year : 2013
Month : 1
Language : English
Paperback : 456 pages
ISBN-10 : 1449339530
ISBN-13 : 978-1449339531
using:
`f = open("C:/Users/Lenovo/Documents/LinuxLab/file.txt",mode = 'r',encoding='utf-8')
for line in f:
print(line)`
the result is the following:
Title : Linux System Programming Talking Directly to the Kernel and C Library
O'Reilly Media : Publisher
Edition : 2
Year : 2013
Month : 1
English : Language
456 pages : Paperback
1449339530 : ISBN-10
978-1449339531: ISBN-13
Here is an implementation for this problem:
def read_book_details(file_path):
book_details = {}
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
line = line.strip()
if line:
key, value = line.split(':', 1)
book_details[key.strip()] = value.strip()
return book_details
# Usage example
file_path = 'books.txt' # Replace with the actual file path
book_details = read_book_details(file_path)
# Print the extracted details
for key, value in book_details.items():
print(f'{key}: {value}')
I have used the key value format to arrange in the given output format.