Python 3.x
Im trying to read from a file called numbers.txt. There are several rows of numbers in it. I need to print the total and average. Along with that I need to use exception handling for IOerror and ValueError.
Thank you in advance. I know there is a question like this but the suggestion errors out.
def main():
total = 0.0
length = 0.0
average = 0.0
try:
filename = raw_input('Enter a file name: ')
infile = open(filename, 'r')
for line in infile:
print (line.rstrip("\n"))
amount = float(line.rstrip("\n"))
total += amount
length = length + 1
average = total / length
infile.close()
print ('There were', length, 'numbers in the file.')
print (format(average, ',.2f'))
except IOError:
print ('An error occurred trying to read the file.')
except ValueError:
print ('Non-numeric data found in the file')
except:
print('An error has occurred')
with open('numbers.txt', 'r') as my_file:
try:
data = [float(n) for n in my_file.read().split()]
except (IOError, ValueError):
data = []
total = sum(data)
average = total / len(data)
print('Numbers: {nums}\nTotal: {total}\nAverage: {average}'.format(nums = data, total = total, average = average))
For future reference, because this is fairly simple code, you can Google each part separately and you can piece them together.
Related
I'm writing a program that uses exceptions to handle errors from multiple text files, one of which being empty. If it's empty, I need to print out a statement saying said file is empty. I have tried 'except EOFError', but that's not correct.
Code:
def main():
process_file("good_data.txt")
process_file("bad_data.txt")
process_file("empty_file.txt")
process_file("does_not_exist.txt")
def process_file(param_str_file_name):
#Variables
num_rec = 0
total = 0
average = 0
try:
file_name = open(param_str_file_name, 'r')
print("Processing file", param_str_file_name)
one_score = file_name.readline()
while one_score != "":
one_score_int = int(one_score)
num_rec = num_rec + 1
one_score = file_name.readline()
total += one_score_int
average = total / num_rec
file_name.close()
print("\tRecord count = ", num_rec)
print("\tTotal = ", total)
print("\tAverage = ", f"{average:.2f}", "\n")
except EOFError:
print("\tError!", param_str_file_name,
" is empty. Cannot calculate average\n")
except FileNotFoundError:
print("\tError!", param_str_file_name, " File not found\n")
except ValueError:
print("\tError!", param_str_file_name, "contains non-numeric data\n")
if __name__ == "__main__":
main()
Output:
Processing file good_data.txt
Record count = 6
Total = 281
Average = 46.83
Processing file bad_data.txt
Error! bad_data.txt contains non-numeric data
Processing file empty_file.txt
Record count = 0
Total = 0
Average = 0.00
Error! does_not_exist.txt File not found
It's just this one little thing to wrap up. Thanks for the help.
Here is a simple way to check if file is empty or not:
import os
size = os.path.getsize('file.txt')
if size > 0:
print ("The file is not empty")
else:
print ("The file is empty")
I'm trying to incorporate enumerate so I can give the user of the program where the line error was and the input of that line.
Here is my code:
elif response == 'data2':
print('Processing file:', response + '.txt')
try:
infile = open('data2.txt', 'r')
for line in infile:
amount = float(line)
total += amount
infile.close()
print(format(total, ',.2f'))
except IOError:
print("IO Error occurred trying to read the file.")
except ValueError:
print("Non-numeric data found in file:", response + '.txt')
except:
print("An error occurred.")
As you see I want the ValueErrorto output something along the lines of:
Non-numeric data found in file: data2.txt at line: 3 with input: three
hundred
I'm however stuck on how to accomplish this.
You can use the enumerate built-in function to get the line number:
elif response == 'data2':
print('Processing file:', response + '.txt')
try:
# Python allows you to iterate over a file object directly.
for line_no, line in enumerate(open('data2.txt', 'r')):
amount = float(line)
total += amount
print(format(total, ',.2f'))
except IOError:
print("IO Error occurred trying to read the file.")
except ValueError:
# I took the liberaty of formatting your output in a way
# that's a bit more readble than one long line of text.
print("Non-numeric data found in file: {}.txt at line: {}"
"with input: {}".format(response, line_no + 1, line))
except:
print("An error occurred.")
You need to track what line you are up to in the file, and catch the exception while reading.
for line_number, line in enumerate(infile, 1):
try:
amount = float(line)
except ValueError:
print(
"Non-numeric data found in file",
response + ".txt on line",
line_number,
"with input",
line
)
exit(1) # or whatever is appropriate for this script.
I have to write a program that will read data from a file, convert it to an integer and total the amount. So far here is what i have. The numbers from the data file "numdata.txt" are: 78,93,85,100,81,76,94,77.
def main():
total = 0
try:
NumberFile = open('numdata.txt', 'r')
for line in NumberFile:
amount = float(line)
total += amount
print(format(total, ',.2f'))
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error has occurred.')
finally:
NumberFile.close()
main()
When i run the program the first number (78) gets displayed and then one of the exception error messages comes up, the weird thing is that it's different sometimes. If someone could help point me in the right direction I'd appreciate it. I'm still very new to this so please bear with me.
I tried and tried but could not get the loop to work correctly so i ended up going this route:
def main ():
infile = open('numdata.txt', 'r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
num4 = int(infile.readline())
num5 = int(infile.readline())
num6 = int(infile.readline())
num7 = int(infile.readline())
num8 = int(infile.readline())
infile.close()
total = num1+num2+num3+num4+num5+num6+num7+num8
average = total/8
print('the total: ', total)
print('the average: ', average)
main()
It's not pretty but it works i guess lol
total = 0
try:
NumberFile = open('numdata.txt', 'r')
for line in NumberFile:
amount = float(line)
total += amount
print(format(total, ',.2f'))
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error has occurred.')
finally:
NumberFile.close()
The exception occurs because you're closing the file immediately after the first iteration, leaving you unable to iterate over the rest of it.
Moving NumberFile.close() to a finally clause ensures the file is closed no matter what goes wrong. However, a much better way to read / write files in Python is to use the with keyword, which is a built-in method of ensuring the same thing.
total = 0
with open('numdata.txt', 'r') as f:
for line in f:
try:
total += float(line)
except ValueError:
print('Non-numeric data found in the file.')
continue
finally:
print('{:.2f}'.format(total, ',.2f'))
you are closing the file in first iteration NumberFile.close() is not indented properly
I am a complete beginner learning python through an online textbook and this is one of the exercises:
Write a program to prompt for a file name, and then read through the
file and look for lines of the form:
X-DSPAM-Confidence:0.8475
When you encounter a line that starts with “X-DSPAM-Confidence:” pull
apart the line to extract the floating-point number on the line. Count
these lines and then compute the total of the spam confidence values
from these lines. When you reach the end of the file, print out the
average spam confidence.
Enter the file name: mbox.txt
Average spam confidence: 0.894128046745
Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519
This is the code I've written so far:
fname = input('Enter file name: ')
count = 0
total = 0
try:
fhand = open(fname)
for line in fhand:
if line.strip().startswith('X-DSPAM-Confidence:'):
count = count + 1
flt = float(line.split(':')[1])
total = total + flt
print(total / count)
except:
print('Bad file name: ', fname)
The output is a long list of numbers, although the final number in the list gives me the correct answer for both 'mbox.txt' and 'mbox-short.txt'. What do I need to change in this code to get it to print only the correct answer?
Only print after your loop is done.
fname = input('Enter file name: ')
count = 0
total = 0
try:
fhand = open(fname)
for line in fhand:
if line.strip().startswith('X-DSPAM-Confidence:'):
count = count + 1
flt = float(line.split(':')[1])
total = total + flt
print(total / count)
except:
print('Bad file name: ', fname)
I'm trying to write a simple exception handling. However it seems I'm doing something wrong.
def average():
TOTAL_VALUE = 0
FILE = open("Numbers.txt", 'r')
for line in FILE:
AMOUNT = float(line)
TOTAL_VALUE += AMOUNT
NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
print("the average of the numbers in 'Numbers.txt' is :",
format(NUMBERS_AVERAGE, '.2f'))
FILE.close()
except ValueError,IOError as err:
print(err)
average()
> line 14
> except ValueError as err:
> ^
> SyntaxError: invalid syntax
There are two things wrong here. First, You need parenthesis to enclose the errors:
except (ValueError,IOError) as err:
Second, you need a try to go with that except line:
def average():
try:
TOTAL_VALUE = 0
FILE = open("Numbers.txt", 'r')
for line in FILE:
AMOUNT = float(line)
TOTAL_VALUE += AMOUNT
NUMBERS_AVERAGE = TOTAL_VALUE / AMOUNT
print("the average of the numbers in 'Numbers.txt' is :",
format(NUMBERS_AVERAGE, '.2f'))
FILE.close()
except (ValueError,IOError) as err:
print(err)
except cannot be used without try.