Python File Handling Exercises and Solutions, Exams of Public Health

A series of exercises focused on file handling in python, along with their corresponding solutions. It covers essential operations such as opening, reading, writing, and manipulating files. The exercises range from basic tasks like reading data from a file to more complex scenarios such as creating and copying files based on specific conditions. These exercises are designed to enhance understanding of file i/o operations, error handling, and data processing techniques in python. It is suitable for students learning python programming and those looking to improve their file handling skills. Practical examples and clear solutions, making it a valuable resource for hands-on learning and skill development in python programming.

Typology: Exams

2025/2026

Available from 10/24/2025

may-blessed
may-blessed 🇺🇸

4.1

(8)

31K documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
MyProgrammingLab Starting out with Python Ch.6
Open the file hostdata.txt for reading. Correct Ans -
open('hostdata.txt', 'r')
Open the file winterdata.txt for reading. Correct Ans -
open('winterdata.txt','r')
Store four file objects corresponding to the files winter2003.txt ,
spring2003.txt, summer2003.txt, and fall2003.txt in the variables winter,
spring, summer, and fall (respectively), and open them all for reading.
Correct Ans - winter = open('winter2003.txt', 'r')
spring = open('spring2003.txt', 'r')
summer = open('summer2003.txt', 'r')
fall = open('fall2003.txt', 'r')
Write a statement to open the file yearsummary.txt in a way that erases any
existing data in the file. Correct Ans - open('yearsummary.txt','w')
Write a statement to open the file priceList.txt for writing. Correct Ans
- open('priceList.txt', 'w')
Given four files named asiasales2009.txt, europesales2009.txt,
africasales2009.txt, and latinamericasales2009.txt, define four file objects
named asia, europe, africa, and latin, and use them, respectively, to open
the four files for writing. Correct Ans - asia =
open('asiasales2009.txt', 'w')
europe = open('europesales2009.txt', 'w')
africa = open('africasales2009.txt','w')
latin = open('latinamericasales2009.txt', 'w')
Given a file named execution.log write the necessary code to add the line
"Program Execution Successful" to the end of the file (add the statement on
a new line).
SUBMIT Correct Ans - thefile =open('execution.log','a')
thefile.write("\nProgram Execution Successful")
thefile.close()
Given a file object named output, associate it with a file named
yearsummary.txt by opening the file for appending Correct Ans -
output = open('yearsummary.txt','a')
Given that corpdata is a file object used for reading data and that there is
no more data to be read, write the necessary code to complete your use of
this object. Correct Ans - corpdata.close()
pf3
pf4
pf5

Partial preview of the text

Download Python File Handling Exercises and Solutions and more Exams Public Health in PDF only on Docsity!

MyProgrammingLab Starting out with Python Ch. Open the file hostdata.txt for reading. Correct Ans - open('hostdata.txt', 'r') Open the file winterdata.txt for reading. Correct Ans - open('winterdata.txt','r') Store four file objects corresponding to the files winter2003.txt , spring2003.txt, summer2003.txt, and fall2003.txt in the variables winter, spring, summer, and fall (respectively), and open them all for reading. Correct Ans - winter = open('winter2003.txt', 'r') spring = open('spring2003.txt', 'r') summer = open('summer2003.txt', 'r') fall = open('fall2003.txt', 'r') Write a statement to open the file yearsummary.txt in a way that erases any existing data in the file. Correct Ans - open('yearsummary.txt','w') Write a statement to open the file priceList.txt for writing. Correct Ans

  • open('priceList.txt', 'w') Given four files named asiasales2009.txt, europesales2009.txt, africasales2009.txt, and latinamericasales2009.txt, define four file objects named asia, europe, africa, and latin, and use them, respectively, to open the four files for writing. Correct Ans - asia = open('asiasales2009.txt', 'w') europe = open('europesales2009.txt', 'w') africa = open('africasales2009.txt','w') latin = open('latinamericasales2009.txt', 'w') Given a file named execution.log write the necessary code to add the line "Program Execution Successful" to the end of the file (add the statement on a new line). SUBMIT Correct Ans - thefile =open('execution.log','a') thefile.write("\nProgram Execution Successful") thefile.close() Given a file object named output, associate it with a file named yearsummary.txt by opening the file for appending Correct Ans - output = open('yearsummary.txt','a') Given that corpdata is a file object used for reading data and that there is no more data to be read, write the necessary code to complete your use of this object. Correct Ans - corpdata.close()

Use the file object output to write the string "3.14159" to a file called pi. Correct Ans - output = open('pi','a') output.write('3.14159') output.close() Using the file object input, write code that read an integer from a file called rawdata into a variable datum (make sure you assign an integer value to datum). Open the file at the beginning of your code, and close it at the end. Correct Ans - input= open('rawdata','r') datum=int(input.read()) input.close() A file named numbers.txt contains an unknown number of lines, each consisting of a single integer. Write some code that computes the sum of all these integers, and stores this sum in a variable name sum. Correct Ans - sum = 0 f = open('numbers.txt', 'r') for line in f: sum += int(line) A file named numbers.txt contains an unknown number of lines, each consisting of a single positive integer. Write some code that reads through the file and stores the largest number read in a variable named maxvalue. Correct Ans - file = open('numbers.txt', 'r') maxvalue= for line in file: if maxvalue <= int (line): maxvalue = int (line) print ('maxvalue is:',maxvalue) A file named data1.txt contains an unknown number of lines, each consisting of a single integer. Write some code that creates a file named data2.txt and copies all the lines of data1.txt to data2.txt. Correct Ans

  • f1 = open('data1.txt', 'r') f2 = open('data2.txt', 'w') for line in f1: f2.write(line) A file named data.txt contains an unknown number of lines, each consisting of a single integer. Write some code that creates two files, dataplus.txt and dataminus.txt, and copies all the lines of data1.txt that have positive integers to dataplus.txt, and all the lines of data1.txt that have negative

scalar_product = 0 num1 = file1.readline() num2 = file2.readline() while (num1 != '') and (num2 != ''): n1 = int(num1) n2 = int(num2) scalar_product += (n1 * n2) num1 = file1.readline() num2 = file2.readline() file1.close() file2.close() Two variables, x and y, supposedly hold strings of digits. Write code that converts these to integers and assigns a variable z the sum of these two integers. Make sure that if either x and y has bad data (that is, not a string of digits), z will be assigned the value of -1. Correct Ans - z = 0 try: z += int(x) + int(y) except ValueError: z = - Two variables, num_boys and num_girls, hold the number of boys and girls that have registered for an elementary school. The variable budget holds the number of dollars that have been allocated to the school for the school year. Write code that prints out the per-student budget (dollar spent per student). If a division by zero error takes place, just print out the word "unavailable". Correct Ans - try: print(budget / (num_boys + num_girls)) except ZeroDivisionError: print('unavailable') Assume that a file containing a series of integers is named numbers.txt. Write a program that calculates the average of all the numbers stored in the file. Correct Ans - def main(): avg_nums = open('numbers.txt','r') total = 0 numberoflines= line = avg_nums.readline() while line != '':

numberoflines+= total+= int(line) line = avg_nums.readline() average = total/numberoflines print(average) avg_nums.close() main() The Springfork Amateur Golf Club has a tournament every weekend. The club president has asked you to write a program that will read each player's name and score as keyboard input, and then save these as records in a file named golf.txt. First, have the program ask the user how many players they want to add to their record. Then, ask the user for each name and score individually. golf.txt should be structured so that there is a line with the player's name, folowed by their score on the next line. Emily 30 Mike 20 Jonathan 23 Correct Ans - num_players = int(input("Enter number of players:")) outfile = open("golf.txt",'w') for i in range(num_players): name = input("Enter name of player number "+str(i+1)+":") score = input("Enter score of player number "+str(i+1)+":") outfile.write(name) outfile.write('\n') outfile.write(score) outfile.write('\n') outfile.close()