Programming Challenge: File Handling and Dictionary Manipulation in Python

Introduction

Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since multiple shows could have the same number of seasons).

Current Code

def readFile(filename):

dict = {}

with open(filename, 'r') as infile:

lines = infile.readlines()

for index in range(0, len(lines) - 1, 2):

if lines[index].strip() == '': continue

count = int(lines[index].strip())

name = lines[index + 1].strip()

if count in dict.keys():

name_list = dict.get(count)

name_list.append(name)

name_list.sort()

else:

dict[count] = [name]

print(count, name)

return dict

Output Functions

def output_keys(dict, filename):

with open(filename, 'w+') as outfile:

for key in sorted(dict.keys()):

outfile.write('{}: {}\\n'.format(key, '; '.join(dict.get(key)))

print('{}: {}\\n'.format(key, ';'.join(dict.get(key)))

def output_titles(dict, filename):

titles = []

for title in dict.values():

titles.extend(title)

with open(filename, 'w+') as outfile:

for title in sorted(titles):

outfile.write('{}\\n'.format(title))

print(title)

Main Function

def main():

filename = input('Enter input file name: ')

dict = readFile(filename)

if dict is None:

print('Error: Invalid file name provided: {}'.format(filename))

return

print(dict)

output_filename_1 = 'output_keys.txt'

output_filename_2 = 'output_titles.txt'

output_keys(dict, output_filename_1)

output_titles(dict, output_filename_2)

Question:

What is the purpose of the provided Python program?

Answer:

The purpose of the provided Python program is to read an input file containing an unsorted list of number of seasons and TV shows, create a dictionary where the number of seasons are the keys and a list of TV shows are the values, sort the dictionary by keys and output the results to two separate files named output_keys.txt and output_titles.txt.

← How do multi core processors enhance performance How to identify pipe fittings →