Jul-17-2019, 03:18 AM
I need to read numbers from a txt file
cal the avg of these numbers
then handle any IO error exceptions that are raised when the file is opened and data is read from it
i was able to accomplish it with a "Import Re" and then using those functions, but since thats not what we learned i am trying to do without.
then trying to figure out what shes asking at the end for handling IOerrors, this part of the book is strange to understand
btw the working code i was able to form with the import re is below, works but trying to create python file without using this and adding the IOErrors / handling
if i take
cal the avg of these numbers
then handle any IO error exceptions that are raised when the file is opened and data is read from it
with open('nums.txt') as f: fdata=f.read() print(fdata) myList = [] for A in fdata: myList.append(int(A)) print("Total =", sum(myList)) def Average(myList): return sum(myList) / len (myList) print("Average =", round(Average(myList), 2)) except ValueError: pass^^ with above got the numbers to read off, im having issues placing these in a list then having that list calculated.
i was able to accomplish it with a "Import Re" and then using those functions, but since thats not what we learned i am trying to do without.
then trying to figure out what shes asking at the end for handling IOerrors, this part of the book is strange to understand
btw the working code i was able to form with the import re is below, works but trying to create python file without using this and adding the IOErrors / handling
import re with open('nums.txt') as f: fdata=f.read() print(fdata) numbers=re.findall('[0-9]+', fdata) myList = [] for A in numbers: myList.append(int(A)) print("Total =", sum(myList)) def Average(myList): return sum(myList) / len (myList) print("Average =", round(Average(myList), 2))
if i take
except ValueError: passill get a message back
Traceback (most recent call last): File "C:\Users\Section9\Desktop\Python Programming\Labs\Lab 6\test 4.py", line 9, in <module> myList.append(int(A)) ValueError: invalid literal for int() with base 10: '\n'