Python Forum
Handling IO Error / Reading from file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Handling IO Error / Reading from file
#1
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

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:
    pass
ill 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'
Reply
#2
'except' is part of 'try' statement so you can't use it without 'try' part:

>>> help('try')
The "try" statement
*******************

The "try" statement specifies exception handlers and/or cleanup code
for a group of statements:

   try_stmt  ::= try1_stmt | try2_stmt
   try1_stmt ::= "try" ":" suite
                 ("except" [expression ["as" identifier]] ":" suite)+
                 ["else" ":" suite]
                 ["finally" ":" suite]
   try2_stmt ::= "try" ":" suite
                 "finally" ":" suite

The "except" clause(s) specify one or more exception handlers. When no
exception occurs in the "try" clause, no exception handler is
executed. When an exception occurs in the "try" suite, a search for an
exception handler is started.  This search inspects the except clauses
in turn until one is found that matches the exception.  An expression-
less except clause, if present, must be last; it matches any
exception.  For an except clause with an expression, that expression
is evaluated, and the clause matches the exception if the resulting
object is “compatible” with the exception.  An object is compatible
with an exception if it is the class or a base class of the exception
object or a tuple containing an item compatible with the exception.

If no except clause matches the exception, the search for an exception
handler continues in the surrounding code and on the invocation stack.
[1]

If the evaluation of an expression in the header of an except clause
raises an exception, the original search for a handler is canceled and
a search starts for the new exception in the surrounding code and on
the call stack (it is treated as if the entire "try" statement raised
the exception).

When a matching except clause is found, the exception is assigned to
the target specified after the "as" keyword in that except clause, if
present, and the except clause’s suite is executed.  All except
clauses must have an executable block.  When the end of this block is
reached, execution continues normally after the entire try statement.
(This means that if two nested handlers exist for the same exception,
and the exception occurs in the try clause of the inner handler, the
outer handler will not handle the exception.)

When an exception has been assigned using "as target", it is cleared
at the end of the except clause.  This is as if

   except E as N:
       foo

was translated to

   except E as N:
       try:
           foo
       finally:
           del N

This means the exception must be assigned to a different name to be
able to refer to it after the except clause.  Exceptions are cleared
because with the traceback attached to them, they form a reference
cycle with the stack frame, keeping all locals in that frame alive
until the next garbage collection occurs.

Before an except clause’s suite is executed, details about the
exception are stored in the "sys" module and can be accessed via
"sys.exc_info()". "sys.exc_info()" returns a 3-tuple consisting of the
exception class, the exception instance and a traceback object (see
section The standard type hierarchy) identifying the point in the
program where the exception occurred.  "sys.exc_info()" values are
restored to their previous values (before the call) when returning
from a function that handled an exception.

The optional "else" clause is executed if and when control flows off
the end of the "try" clause. [2] Exceptions in the "else" clause are
not handled by the preceding "except" clauses.

If "finally" is present, it specifies a ‘cleanup’ handler.  The "try"
clause is executed, including any "except" and "else" clauses.  If an
exception occurs in any of the clauses and is not handled, the
exception is temporarily saved. The "finally" clause is executed.  If
there is a saved exception it is re-raised at the end of the "finally"
clause.  If the "finally" clause raises another exception, the saved
exception is set as the context of the new exception. If the "finally"
clause executes a "return" or "break" statement, the saved exception
is discarded:

   >>> def f():
   ...     try:
   ...         1/0
   ...     finally:
   ...         return 42
   ...
   >>> f()
   42

The exception information is not available to the program during
execution of the "finally" clause.

When a "return", "break" or "continue" statement is executed in the
"try" suite of a "try"…"finally" statement, the "finally" clause is
also executed ‘on the way out.’ A "continue" statement is illegal in
the "finally" clause. (The reason is a problem with the current
implementation — this restriction may be lifted in the future).

The return value of a function is determined by the last "return"
statement executed.  Since the "finally" clause always executes, a
"return" statement executed in the "finally" clause will always be the
last one executed:

   >>> def foo():
   ...     try:
   ...         return 'try'
   ...     finally:
   ...         return 'finally'
   ...
   >>> foo()
   'finally'

Additional information on exceptions can be found in section
Exceptions, and information on using the "raise" statement to generate
exceptions may be found in section The raise statement.

Related help topics: EXCEPTIONS
(END)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
so can i still apply this even though i get no errors with the system to complete objectives?

updated working code without importing "RE"
    with open('nums.txt') as nums_file:
        numbers = []
        for line in nums_file:
            numbers.append(int(line))
    print(numbers)
    print("Total =", sum(numbers))
    def Average(numbers):
        return sum(numbers) / len (numbers)
    print("Average =", round(Average(numbers), 2))
Reply
#4
Make a function that only do file reading with exception handling,then can add other function and also make one function for total sum.
Eg:
def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"

if __name__ == '__main__':
    file_in = 'nums.txt' # Test with different input
    print(read_data(file_in))
OSError is a top level exceptions.
Quote:Changed in version 3.3: EnvironmentError, IOError, WindowsError, socket.error, select.error and mmap.error
have been merged into OSError, and the constructor may return a subclass.
Reply
#5
(Jul-17-2019, 07:00 PM)snippsat Wrote: Make a function that only do file reading with exception handling,then can add other function and also make one function for total sum.
Eg:
def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"

if __name__ == '__main__':
    file_in = 'nums.txt' # Test with different input
    print(read_data(file_in))

That works for raising an error when changing the nums.txt
now the question is fitting back in the
print("Total =", sum(numbers))
def Average(numbers):
    return sum(numbers) / len (numbers)
print("Average =", round(Average(numbers), 2))
getting error that
print("Total =", sum(numbers))
NameError: name 'numbers' is not defined

Oh just did some weird stuff and output does not look happy lol
But i think i got closer
def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
                print("Total =", sum(numbers))
                def Average(numbers):
                    return sum(numbers) / len (numbers)
                print("Average =", round(Average(numbers), 2))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"

    
if __name__ == '__main__':
    file_in = 'nums.txt' # Test with different input
    print(read_data(file_in))
    
except output is
Total = 95
Average = 95.0
Total = 185
Average = 92.5
Total = 274
Average = 91.33
Total = 327
Average = 81.75
Total = 415
Average = 83.0
Total = 515
Average = 85.83
Total = 616
Average = 88.0
Total = 651
Average = 81.38
Total = 723
Average = 80.33
Total = 816
Average = 81.6
Total = 903
Average = 82.09
Total = 966
Average = 80.5
Total = 1066
Average = 82.0
Total = 1164
Average = 83.14
Total = 1239
Average = 82.6
Total = 1304
Average = 81.5
Total = 1384
Average = 81.41
Total = 1476
Average = 82.0
Total = 1501
Average = 79.0
[95, 90, 89, 53, 88, 100, 101, 35, 72, 93, 87, 63, 100, 98, 75, 65, 80, 92, 25]
Reply
#6
Do not add stuff to read_data function it should only do that.
If add average function that you have it would look like this.
Then make also a function for total sum.
def average(numbers):
    avg = sum(numbers) / len (numbers)
    print(f"Average = {avg:.2f}")

def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"

if __name__ == '__main__':
    file_in = 'nums.txt'
    numbers = read_data(file_in)
    average(numbers)
Reply
#7
(Jul-17-2019, 09:58 PM)snippsat Wrote: Do not add stuff to read_data function it should only do that.
If add average function that you have it would look like this.
Then make also a function for total sum.
def average(numbers):
    avg = sum(numbers) / len (numbers)
    print(f"Average = {avg:.2f}")

def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"

if __name__ == '__main__':
    file_in = 'nums.txt'
    numbers = read_data(file_in)
    average(numbers)

ok looks like the final output would be
def average(numbers):
    avg = sum(numbers) / len (numbers)
    print(f"Average = {avg:.2f}")
 
def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"
 
if __name__ == '__main__':
    file_in = 'nums.txt'
    numbers = read_data(file_in)
    print(numbers)
    print("Total =", sum(numbers))
    average(numbers)
which meets all my conditions, you guys are awesome.
so i only have a few more questions just for understanding purposes.
explanations of a few quotes and wondering what it exactly does

if __name__ == '__main__':
    print(f"Average = {avg:.2f}")

WELLLLLLL NM
it did work then i restarted it and it broke
Reply
#8
Expel Wrote:if __name__ == '__main__':
Could have removed and it would make no difference running code now.
If import code it would not have run code after that line,it's good practice to use it.
Usually when import code we do not want it to run at import time.
Expel Wrote:print(f"Average = {avg:.2f}")
Search for f-string,it's a new(Python 3.6+) and better way to format strings.
>>> n = 10.123456789
>>> print(f"Average = {n:.2f}")
Average = 10.12
>>> print(f"Average = {n:.3f}")
Average = 10.123
>>> print(f"Average = {n:.1f}")
Average = 10.1
Reply
#9
Confused on this still, removed it and it broke.
(Jul-17-2019, 10:23 PM)snippsat Wrote:
Expel Wrote:if __name__ == '__main__':
Could have removed and it would make no difference running code now.
If import code it would not have run code after that line,it's good practice to use it.
Usually when import code we do not want it to run at import time.
So when you say import you mean something like
>>> import sys
>>> sys.path
['',
'C:\\Users\\Section9\\Desktop\\Python Programming\\Labs\\Lab 6\\nums.txt']
Ah thatnx easily understandable!!!!
(Jul-17-2019, 10:23 PM)snippsat Wrote:
Expel Wrote:print(f"Average = {avg:.2f}")
Search for f-string,it's a new(Python 3.6+) and better way to format strings.
>>> n = 10.123456789
>>> print(f"Average = {n:.2f}")
Average = 10.12
>>> print(f"Average = {n:.3f}")
Average = 10.123
>>> print(f"Average = {n:.1f}")
Average = 10.1

Also the
except OSError:
        return f"Could not read file: {file_in}"
now is broken, i think i need to move it to cause it to work again

.
.
.
.
.
ok figured part of it out on how to remove
it was just "import sys"
but now got to fix the OSERROR
import sys
def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"

def average(numbers):
    avg = sum(numbers) / len (numbers)
    print(f"Average = {avg:.2f}")

file_in = 'nums.txt'
numbers = read_data(file_in)
print(numbers)
print("Total =", sum(numbers))
average(numbers)
when i change the num.txt file in the
file_in = 'numsx.txt'
i get this error now
Could not read file: numsx.txt
Traceback (most recent call last):
  File "C:\Users\Section9\Desktop\Python Programming\Labs\Lab 6\test7.py", line 19, in <module>
    print("Total =", sum(numbers))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Reply
#10
Found new way to write to get half and half
i can change the file name and get the "Could not read file" line to work
but id still have to print off the total and average because i couldn't find a way to stick those lines in there and turn them off and on when i change text file name

def read_data(file_in):
    try:
        with open(file_in) as nums_file:
            numbers = []
            for line in nums_file:
                numbers.append(int(line))
        return numbers
    except OSError:
        return f"Could not read file: {file_in}"
 

file_in = 'nums.txt' # Test with different input
print(read_data(file_in))
    
def average(numbers):
    avg = sum(numbers) / len (numbers)
    print(f"Average = {avg:.2f}")
    
file_in = 'nums.txt'
numbers = read_data(file_in)
print("Total =", sum(numbers))
average(numbers)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Excel File reading vanjoe198 1 2,026 Mar-31-2021, 11:53 AM
Last Post: snippsat
  reading from a file looseCannon101 14 4,871 Jul-18-2020, 11:29 AM
Last Post: GOTO10
  Weird problem with reading from file and performing calculations pineapple999 1 2,994 Jul-25-2019, 01:30 AM
Last Post: ichabod801
  Reading an Unconventional CSV file OzSbk 2 3,865 May-17-2019, 12:15 PM
Last Post: MvGulik
  reading text file and writing to an output file precedded by line numbers kannan 7 10,369 Dec-11-2018, 02:19 PM
Last Post: ichabod801
  Reading of structured .mat (matlab) file sumit 2 3,408 May-24-2018, 12:12 PM
Last Post: sumit
  File Reading toxicxarrow 9 5,165 May-07-2018, 04:12 PM
Last Post: toxicxarrow
  reading all lines from a text file seadoofanatic 2 2,916 Mar-13-2018, 06:05 PM
Last Post: Narsimhachary
  Reading a text file fivestar 7 5,564 Oct-13-2017, 07:25 AM
Last Post: gruntfutuk
  Is there a specialist in error handling ? sylas 9 6,096 May-22-2017, 03:17 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020