Chapter 6 Files and Exceptions
Write a statement to open the file priceList.txt for writing.
open('priceList.txt', 'w')
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)
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()
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 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)
Open the file hostdata.txt for reading.
hostdata_txt = open('hostdata.txt', 'r')
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()
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.
minus = open('dataminus.txt', 'a') plus = open('dataplus.txt', 'a') source = open('data.txt', 'r') sor = source.readline() while sor != '': x = int(sor) if (x > 0): plus.write(str(x)+'\n') elif (x < 0): minus.write(str(x)+'\n') sor = source.readline() source.close() minus.close() plus.close()
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.
num1 = open('numbers1.txt', 'r') num2 = open('numbers2.txt', 'r') scalar_product = 0 num1line = num1.readline() num2line = num2.readline() while num1line != '' and num2line != '': num1line = int(num1line) num2line = int(num2line) scalar_product += (num1line * num2line) num1line = num1.readline() num2line = num2.readline()
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).
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')
Three variables, x, y and z, supposedly hold strings of digits, suitable for converting to integers. Write code that converts these to integers and print the sum of these three integers. However, if any variable has a value that cannot be converted to an integer, print out, the string "bad value(s) in: " followed by the names of the variables that have bad values (separated by spaces, in alphabetically ascending order). For example, if the values of x, y and z were respectively "3", "9", "2" then the number 14 would be printed; but if the values were "abc", "15", "boo" then the output would be: bad value(s) in: x z
try: sum = int(x) + int(y) + int(z) print(sum) except ValueError: print("bad value(s) in:",end='') if not x.isdigit(): print(' x',end='') if not y.isdigit(): print(' y',end='') if not z.isdigit(): print(' z',)
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')
Open the file winterdata.txt for reading.
winterdata_txt = open('winterdata.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