Friday, June 24, 2016

Introduction to network programming - Files and Exception Handling


Hi,
In this  post i attached my lecture 4 which has chapter 7, here i an going to post practice questions and tutorial for chapter 7

here, you can find lecture slides,



Programming Exercises
you can find these exercise questions at the end of the chapter 7 in this book




1. File Display
Assume that a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that displays all of the numbers in the file.
answer :-

write to file :

File_variable = open("numbers.txt",'w')

for num in range(1,56):
    File_variable.write(str(num) + '\n')
File_variable.close()


read from file:


File_variable = open("numbers.txt",'r')
for line in File_variable:
    number = int(line)
    print(number)
File_variable.close()


2. File Head Display

Write a program that asks the user for the name of a file. The program should display only the first five lines of the file’s contents. If the file contains less than five lines, it should display the file’s entire contents.

answer :-
filename = input("Enter the file that you want to read : ")
File_variable = open(filename,'r')
num = 0
line = File_variable.readline()
line = line.rstrip('\n')
while num != 5 and line != "":
    print(line)
    line = File_variable.readline()
    line = line.rstrip('\n')
    num+=1
File_variable.close()

3. Line Numbers
Write a program that asks the user for the name of a file. The program should display the contents of the file with each line preceded with a line number followed by a colon. The line numbering should start at 1.
answer :-


filename = input("Enter the file that you want to read : ")
File_variable = open(filename , 'r')
num = 0
for line in File_variable:
    line = line.rstrip('\n')
    print(num + 1,":",line)
    num += 1 
File_variable.close()

4. Item CounterAssume that a file containing a series of names (as strings) is named names.txt and exists on the computer’s disk. Write a program that displays the number of names that are stored in the file , calculates their total and calculates the average of all the numbers stored in the file. .
(Hint: Open the file and read every string stored in it. Use a variable to keep a count of the number of items that are read from the file.)
Modify the program that  it handles the following exceptions:
• It should handle any IOError exceptions that are raised when the file is opened and data 
is read from it.
• It should handle any ValueError exceptions that are raised when the items that are read 
from the file are converted to a number.
answer :-

try:
    filename = input("Enter the file that you want to read : ")
    File_variable = open(filename , 'r')
    total = 0
    num = 0
    for line in File_variable:
        number = int(line)
        total = total + number
        num += 1
    average = (total / num)
    print(filename,"have",num, \
          "items \nand total of them is :",total, \
          "\nand their vaerage is :",average)
except IOError:
    print(filename,"doesnt exit")
except ValueError:
    print("items that are read from the file are converted to number")



5. Random Number File Writer
Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 100. The application should let the user specify how many random numbers the file will hold.

answer :- 

write to file :- 


import random

filename = input("Enter the file that you want to write : ")
File_variable = open(filename , 'w')
limit = int(input("Enter the limit of random numbers that you want in the list : "))
for line in range(limit):
    number = random.randint(1,100)
    File_variable.write(str(number) + '\n')
File_variable.close()

read from file :-

import random

filename = input("Enter the file that youwant to read : ")
File_variable = open(filename , 'r')
count = 0
print("random numbers are : ")
for line in File_variable:
    number = int(line)
    
    print(number,end =",")
    count += 1
print()
print(filename,"contains : ",count,"random numbers")
File_variable.close()

6. Golf ScoresThe Springfork Amateur Golf Club has a tournament every weekend. The club president has asked you to write two programs:

1. A program that will read each player’s name and golf score as keyboard input, and then save these as records in a file named golf.txt. (Each record will have a field for the player’s name and a field for the player’s score.)

2. A program that reads the records from the golf.txt file and displays them.
answer :-

write to file :- 

fileName = input("Enter the file name you want to write : ")
File_variable = open(fileName , 'w')
member = int(input("Enter the number of members in club  : "))
num = 0
for record in range(member):
    name = input("Enter the  player no "+str(num+1)+" : ")
    score = int(input("Enter the score that scored by "+" " +name + " : " ))
    File_variable.write(name+"\t"+str(score)+"\n")
    num = num + 1
File_variable.close()

read from file :-

fileName = input("Enter the file name you want to read : ")
File_variable = open(fileName , 'r')
num = 0
print("name\tscore")
print("*********************")
for line in File_variable:
        line = line.rstrip('\n')
        print(line)
File_variable.close()



From the tutorial,

Task 1

Create two text files in IDLE (make sure they are unformatted raw text files) named servers.txt and connections.txt. The first of these files stores a list of host names while the second one stores the number of connections for each server for a particular month of the year. For example, the servers.txt and connections.txt might look like the following (you may extend these files or create completely new ones with at least 10 lines each). According to these files www.melbourne.edu.au had 1245 while www.athens.org.gr had 6754 connections for a particular month that the files refer to.

servers.txt 
------------- 
www.melbourne.edu.au 
www.famagusta.com 
www.athens.org.gr 
www.istanbul.com.tr 
…. 

connections.txt 
------------- 
1245 
457 
6754 
2980 
….

Task - 2

Write a menu driven Python program with the following functionality: 
  • When run, the program repeatedly displays a menu with 5 options: 
                      1. Find server connections 
                      2. Find busiest server 
                      3. Add new server 
                      4. Backup files 
                      5. Quit program

  • When option 1 is selected, program asks the user to enter the server name, searches for the server in servers.txt file and if it finds it, it returns the number of connections for that  particular server found in the connections.txt file. If it doesn’t find it in the file, it returns a  message stating that the server doesn’t exist in the file (or some message like “unknown server”).

 • When option 2 is selected, program searches the connections.txt file, finds the largest value in the file and then it returns the corresponding server found in the servers.txt file.

 • When option 3 is selected, program prompts the user for a new server name and the  corresponding number of connections and then adds the server name at the end of  servers.txt file and the number of connections at the end of the connections.txt file.

 • When option 4 is selected, program opens two text files named serversBKUP.txt and connectionsBKUP.txt for writing and then copies the contents of server.txt to the first one  and the contents of connections.txt to the second.

 • When option 5 is selected, the program terminates

answer :-

def main():
    choice = menu()
    while choice != '5':
        if choice == '1':
            serverName = input("Enter the server name : ")
            connections = findOfServer(serverName)
            print("NUmber of Connection for server",serverName,"is",connections)
        elif choice == '2':
            busyServer = busiestServer()
            print("busiest server is",busyServer)
        elif choice == '3':
            serverName = input("Enter new server you want to add : ")
            connections = int(input("Enter the number of connection: "))
            addServer(serverName , connections )
            print("server added to the files")
        elif choice == '4':
            backupFile()
            print("Backing Files up...")
        else :
            print("Invalid input")
            print("Enter number between 1 and 5")
        choice = menu()
    if(choice == '5'):
       print("program terminated") 
        

def findOfServer(serverName):
    
    file_variable1 = open("servers.txt",'r')
    file_variable2 = open("connections.txt",'r')
    
    num = 1
    found = False
    for line in file_variable1:
        line = line.rstrip('\n')
        if(line == serverName):
            found = True
            linea = num
        else :
            num += 1
    file_variable1.close()
    numb = 1
    
    if found:
        for line2 in file_variable2:
             line2 = line2.rstrip('\n')
             if(numb == linea):
                 return line2
             else:
                 numb  += 1
    else:
        print("server not found .....")
    file_variable2.close()


def addServer(serverName , connections):
    file_variable = open("servers.txt","a")
    file_variable.write( serverName + '\n')
    file_variable.close()
    file_variable1 = open("connections.txt",'a')
    file_variable1.write(str(connections) + '\n')
    file_variable1.close()


def busiestServer():
    file_variable1 = open("connections.txt",'r')
    largest_num = 0
    for line in file_variable1:
        line = line.rstrip('\n')
        connect = int(line)
        if(largest_num <= connect):
            largest_num = connect
    print("largest connection is ",largest_num)
    num = 1
    file_variable1.close()
    file_variable1 = open("connections.txt",'r')
    for line1 in file_variable1:
        convert = int(line1)
        if(convert == largest_num):
            line3 = num
        else:
            num += 1
    print("line number of",largest_num,"is",line3)
    file_variable1.close()
    file_variable2 = open("servers.txt",'r')
    number = 1
    for line4 in file_variable2:
        line4 = line4.rstrip('\n')
        if(number == line3):
            return line4
        else:
            number += 1
    file_variable2.close()


def backupFile():
    file_variable = open("servers.txt","r")
    file_backupServer = open("serversBACKUP.txt" , 'w')
    for line in file_variable:
        line = line.rstrip('\n')
        file_backupServer.write(line + '\n')
    file_backupServer.close()
    file_variable.close()

    file_variable1 = open("connections.txt","r")
    file_backupConn = open("connectionsBACKUP.txt" , 'w')
    for line1 in file_variable1:
        line1 = line1.rstrip('\n')
        file_backupConn.write(line1 + '\n')
    file_backupConn.close()
    file_variable1.close()

    
def menu():
    print("The main menu")
    print("----------------")
    print("1.Find server Conncetions")
    print("2.Find busiest server ")
    print("3.Add new server")
    print("4.Backup files")
    print("5.Quiet program")
    print("----------------------------")
    option = input("Enter your selection (1 - 5 ) : ")
    return option
main()
    
     
    
i will post chapter 8(Lists) and chapter 9(String) very soon.... 

No comments:

Post a Comment