MyProgrammingLab Starting out with Python Ch.6

¡Supera tus tareas y exámenes ahora con Quizwiz!

Open the file hostdata.txt for reading.

open('hostdata.txt', 'r')

Write a statement to open the file priceList.txt for writing.

open('priceList.txt', 'w')

Open the file winterdata.txt for reading.

open('winterdata.txt','r')

Write a statement to open the file yearsummary.txt in a way that erases any existing data in the file.

open('yearsummary.txt','w')

Use the file object output to write the string "3.14159" to a file called pi.

output = open('pi','a') output.write('3.14159') output.close()

Given a file object named output, associate it with a file named yearsummary.txt by opening the file for appending

output = open('yearsummary.txt','a')

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, ignoring those value that are not bigger than the maximum value read up to that point. The numbers that are NOT ignored are added, and their sum stored in a variable called runsum. For example, if the sequence of integers in the file were "9 7 5 18 13 2 22 16" the code would ignore: 7, 5, 13, 2 and 16; it would add 9, 18, and 22, storing their sum, 49, into runsum.

runsum=0 max_val=0 with open("numbers.txt") as f: for line in f: num=int(line) if num > max_val: max_val= num runsum=runsum+num print(runsum)

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.

sum = 0 f = open('numbers.txt', 'r') for line in f: sum += int(line)

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.

asia = open('asiasales2009.txt', 'w') europe = open('europesales2009.txt', 'w') africa = open('africasales2009.txt','w') latin = open('latinamericasales2009.txt', 'w')

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.

corpdata.close()

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.

def main(): avg_nums = open('numbers.txt','r') total = 0 numberoflines=0 line = avg_nums.readline() while line != '': numberoflines+=1 total+= int(line) line = avg_nums.readline() average = total/numberoflines print(average) avg_nums.close() main()

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.

f1 = open('data1.txt', 'r') f2 = open('data2.txt', 'w') for line in f1: f2.write(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.

file = open('numbers.txt', 'r') maxvalue=0 for line in file: if maxvalue <= int (line): maxvalue = int (line) print ('maxvalue is:',maxvalue)

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 integers to dataminus.txt. Zeros are not copied anywhere.

file1 = open("data.txt", 'r') file2 = open("dataplus.txt", 'w') file3 = open("dataminus.txt", 'w') for line in file1: line = int(line.strip()) if line > 0: file2.write(str(line) + '\n') elif line < 0: file3.write(str(line) + '\n')

Two files named numbers1.txt and numbers2.txt both have an unknown number of lines, each line consisting of a single positive integer. Write some code that reads a line from one file and then a line from the other file. The two integers are multiplied together and their product is added to a variable called scalar_product which should be initialized to zero. Your code should stop when it detects end of file in either file that it is reading. For example, if the sequence of integers in one file was "9 7 5 18 13 2 22 16" and "4 7 8 2" in the other file, your code would compute: 4*9 + 7*7 + 8*5 + 2*18 and thus store 161 into scalar_product.

file1 = open('numbers1.txt', 'r') file2 = open('numbers2.txt', 'r') 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()

Write a program that reads the records from the golf.txt file written in Exercise 10a and prints them in the following format: Name: Emily Score: 30 Name: Mike Score: 20 Name: Jonathan Score: 23

golf_file = open('golf.txt','r') line=golf_file.readlines() #score='' for i in range(0,len(line),2): print('Name:'+line[i].strip('\n')) print('Score:'+line[i+1].strip('\n')) print() golf_file.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.

input= open('rawdata','r') datum=int(input.read()) input.close()

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

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()

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

thefile =open('execution.log','a') thefile.write("\nProgram Execution Successful") thefile.close()

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".

try: print(budget / (num_boys + num_girls)) except ZeroDivisionError: print('unavailable')

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.

winter = open('winter2003.txt', 'r') spring = open('spring2003.txt', 'r') summer = open('summer2003.txt', 'r') fall = open('fall2003.txt', 'r')

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.

z = 0 try: z += int(x) + int(y) except ValueError: z = -1


Conjuntos de estudio relacionados

Iggy Ch 25 - Care of Patients with Skin Problems

View Set

DR QUIZ 4 - Authorized Relationships, Duties, adn Disclosure

View Set

DMD Lesson 6 Inheritance of Genes

View Set

Chapter 11: LECTURE REASONING AND DECISION MAKING

View Set

Ch. 39 Pt. 2 Anatomy and Physiology

View Set