程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Explain Python exception handling and file reading and writing in detail

編輯:Python

author | pythonic Biological man

source | pythonic Biological man

Sort it out in detail python Exception handling method :try/except/else/finally/raise/assert

 Sort it out in detail python File read and write :open/write

Catalog

1. exception handling
Handle a single exception :try/except
Multiple exceptions are handled in one way : Tuples contain multiple exception types
Multiple exceptions are handled individually : Multiple except sentence
Handle all exceptions :Exception Catch all exceptions
Clean up after the script is executed :finally
Perform some tasks when no exception is triggered :try/else
Actively trigger an exception type :raise
An exception is triggered when a condition is met :assert
python3 Built in standard exception types in
2.Python Reading and writing files in
python3 in open function
Read the entire file at once
Read the file line by line
Overwrite existing content and write to file
Append to file 

1. exception handling

Exception handling is not recommended , Overuse makes the code less readable ; It is recommended to use exception handling when the exception is unpredictable , Try to solve other exceptions .

Handle a single exception :try/except

The code that may trigger an exception will be placed in try In the sentence block , The exception handling code is placed in except In the sentence block .

try:#try An error is reported in any line of code in the code block , The statement after this line of code will not execute , Throw error type .
    file = open('test', 'rb')
except IOError as e:
#IOError Is the exception type , If try The error thrown in is exactly the exception type , perform except The exception is handled by the code in , Program continues , Otherwise, terminate the procedure .
    print('An IOError occurred. {}'.format(e.args[-1]))# Code to handle exceptions  .

An IOError occurred. No such file or directory

Multiple exceptions are handled in one way : Tuples contain multiple exception types

Store all possible exception types in a tuple .

try:
    file = open('test', 'rb')
except (IOError, EOFError) as e:# Multiple exception types are stored in (IOError, EOFError) Tuple
    print("An error occurred. {}".format(e.args[-1]))

An error occurred. No such file or directory

Multiple exceptions are handled individually : Multiple except sentence

Use one for each exception type except Statement block processing

try:
    file = open('test', 'rb')
except EOFError as e:# The except Handle EOFError Types of abnormal
    print("An EOF error occurred.")
except IOError as e:# The except Handle IOFError Types of abnormal
    print("An error occurred.")

An error occurred.

Handle all exceptions :Exception Catch all exceptions

try:
    file = open('test', 'rb')
except Exception as e:#Exception Catch all exception types , Save to args In the tuple of .
    print('All exceptions {}'.format(e.args))

All exceptions (2, 'No such file or directory')

Clean up after the script is executed :finally

finally Code blocks in are executed regardless of whether an exception is triggered , It is often used to clean up after script execution .

try:
    file = open('test', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
finally:# The statement block must execute , No matter what try Whether the code is triggered in , No matter what except Whether to handle exceptions in .
    print("This would be printed whether or not an exception occurred!")

An IOError occurred. No such file or directory
This would be printed whether or not an exception occurred!

Perform some tasks when no exception is triggered :try/else

try The exception in the code block is not triggered , perform else Sentence block .

try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:#try Run when the statement block does not trigger an exception ; Exceptions in this code block are not caught .
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')

I am sure no exception is going to occur!
This would only run if no exception occurs. And an error here would NOT be caught.
This would be printed in every case.

Actively trigger an exception type :raise

try:
    raise IOError(' An actively triggered exception type ')# This exception is triggered automatically
except Exception as e:
    print(e.args)

(' An actively triggered exception type ',)

An exception is triggered when a condition is met :assert

try:
    assert False," front bool Judgment for False Is to trigger an exception "
except Exception as e:
    print(e.args)

(' front bool Judgment for False Is to trigger an exception ',)

python3 Built in standard exception types in

Only a few , Such as ZeroDivisionError、ImportError、IndexError、KeyError、TypeError、ValueError、SystemError Wait for a few .python3 The built-in exception types in and the inheritance relationship between exceptions , See the table below for the trigger causes of each exception type :

python Built in standard exception types

And inheritance (python3.8.3)

Cause of triggering exception

BaseException

The base class for all built-in exceptions .

 +-- SystemExit

sys.exit() Function raises .

 +-- KeyboardInterrupt

When the user presses the interrupt key ( Usually it is Control-C or Delete) Will be triggered .

 +-- GeneratorExit

When a generator generator or coroutine When it is closed, it will be triggered

 +-- Exception

All built-in non system exit class exceptions and custom exceptions are derived from this class .

      +-- StopIteration

Built in functions next() And iterators iterator Of __next__() Method .

      +-- StopAsyncIteration

By a asynchronous iterator Object's __anext__() Method to stop the iterative operation .

      +-- ArithmeticError

Built in exception caused by various arithmetic errors

      |    +-- FloatingPointError

Not currently used , ha-ha ~.

      |    +-- OverflowError

When the result of an arithmetic operation is too large to be represented, it will be thrown .

      |    +-- ZeroDivisionError

Is raised when the denominator of a division or remainder operation is zero .

      +-- AssertionError

When assert(bool Judge the trigger exception ) If the statement fails, it will be thrown .

      +-- AttributeError

Is thrown when the property reference or assignment fails ( See you often ).

      +-- BufferError

It will be thrown when the buffer related operation cannot be performed .

      +-- EOFError

When input() The end of file condition is reached when the function does not read any data (EOF) Will be triggered .

      +-- ImportError

Raised when a module is imported , When import Load modules and from/import Medium "from list" Thrown when there is a name that cannot be found .

      |    +-- ModuleNotFoundError

When a module cannot be located, it will be determined by import trigger , When in sys.modules Find None Will also be triggered .

      +-- LookupError

IndexError,KeyError Exception thrown and codecs.lookup() Directly trigger .

      |    +-- IndexError

Beyond sequence class data structures (list,str etc. ) Will be thrown when indexing a range .

      |    +-- KeyError

Mapping class data structures (dict) Is thrown when a key is not found in the .

      +-- MemoryError

When an operation runs out of memory, but the situation can still ( By deleting some objects ) Rescue will be triggered .

      +-- NameError

Is thrown when a local or global name is not found .

      |    +-- UnboundLocalError

When a local variable is referenced in a function or method , It is thrown when the variable is not bound to any value .

      +-- OSError

Raised according to the system error code .

      |    +-- BlockingIOError

When an operation is set as a non blocking operation by an object ( For example socket ) Will be triggered when blocked .

      |    +-- ChildProcessError

When an operation on a child process fails, it will be thrown . Corresponding to errno ECHILD.

      |    +-- ConnectionError

Base class for connection related exceptions .

      |    |    +-- BrokenPipeError

When trying to write to a pipe whose other end has been closed , Or an attempt to write to a closed socket will be thrown . Corresponding to errno EPIPE and ESHUTDOWN.

      |    |    +-- ConnectionAbortedError

When the connection attempt is aborted by the opposite end . Corresponding to errno ECONNABORTED.

      |    |    +-- ConnectionRefusedError

Thrown when a connection attempt is rejected by the opposite end . Corresponding to errno ECONNREFUSED.

      |    |    +-- ConnectionResetError

Is raised when the connection is reset by the opposite end . Corresponding to errno ECONNRESET.

      |    +-- FileExistsError

When trying to create an existing file or directory, it will be thrown . Corresponding to errno EEXIST.

      |    +-- FileNotFoundError

Is thrown when the requested file or directory does not exist . Corresponding to errno ENOENT.

      |    +-- InterruptedError

When the system call is interrupted by an input signal, it will be raised . Corresponding to errno EINTR.

      |    +-- IsADirectoryError

When a file operation is requested on a directory ( for example os.remove()) Will be triggered . Corresponding to errno EISDIR.

      |    +-- NotADirectoryError

When requesting a directory operation on a non directory object ( for example os.listdir()) Will be triggered . Corresponding to errno ENOTDIR.

      |    +-- PermissionError

When an operation is attempted without sufficient operation permission, it will be thrown —— For example, lack of file system permissions . Corresponding to errno EACCES and EPERM.

      |    +-- ProcessLookupError

When the given process does not exist, it will be thrown . Corresponding to errno ESRCH.

      |    +-- TimeoutError

When a system level timeout occurs in a system function, it will be thrown . Corresponding to errno ETIMEDOUT.

      +-- ReferenceError

This exception will be used in weakref.proxy() Raised when a weak reference created by the function is used to access a property of the reference that has been garbage collected .

      +-- RuntimeError

When an error not belonging to any other category is detected, it will be thrown . The associated value is a string that indicates what happened .

      |    +-- NotImplementedError

In the user-defined base class , An abstract method should overload the method in the class it requires to derive , Or this exception is thrown when it requires the developed class to prompt that the specific implementation has yet to be added .

      |    +-- RecursionError

The interpreter detected that more than the maximum recursion depth was thrown .

      +-- SyntaxError

When the parser encounters a syntax error, it will be thrown .

      |    +-- IndentationError

Syntax error base class associated with incorrect indentation .

      |         +-- TabError

Raised when indentation contains inconsistent use of tabs and spaces .

      +-- SystemError

When the interpreter finds an internal error , But the situation does not seem serious enough to give up all hope .

      +-- TypeError

Raised when an operation or function is applied to an object of an inappropriate type .

      +-- ValueError

When an operation or function receives a parameter with the correct type but an inappropriate value , And the situation cannot use more precise exceptions, such as IndexError Will be triggered when describing .

      |    +-- UnicodeError

When it happens with Unicode A related encoding or decoding error will be raised .

      |         +-- UnicodeDecodeError

When in " The decoding process " Occurs in and Unicode Related errors will be raised .

      |         +-- UnicodeEncodeError

When in " Coding process " Occurs in and Unicode Related errors will be raised .

      |         +-- UnicodeTranslateError

stay " Transcribe process " Occurs in and Unicode Related errors will be raised .

      +-- Warning

The base class of the warning category .

           +-- DeprecationWarning

If the warning is directed at other Python Developer's , This is used as the base class for warnings related to deprecated features .

           +-- PendingDeprecationWarning

For obsolete and expected to be discarded in the future , But the base class for feature related warnings has not been deprecated yet .

           +-- RuntimeWarning

Base class for warnings related to ambiguous runtime behavior .

           +-- SyntaxWarning

Base class for warnings related to ambiguous Syntax .

           +-- UserWarning

Base class for warnings generated by user code .

           +-- FutureWarning

If the warning is directed at Python Of the end user of the application being written , This is used as the base class for warnings related to deprecated features .

           +-- ImportWarning

Base class for warnings related to possible errors in module import .

           +-- UnicodeWarning

And Unicode Base class for related warnings .

           +-- BytesWarning

And bytes and bytearray Base class for related warnings .

           +-- ResourceWarning

The base class for warnings related to resource use . Will be ignored by the default warning filter .


2.Python Reading and writing files in

python3 in open function

grammar :open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file, Open file ;
mode, Turn on mode , The default is ‘r’ Read mode ;
The details are as follows :

character

meaning

'r'

Read ( Default )

'w'

Overwrite write , If there is something in the file , Coverage

'x'

Exclusive creation , Fail if file already exists

'a'

Append write , If the file already contains , Add... At the end

'b'

Binary mode

't'

Text mode ( Default )

'+'

Update disk files ( Read and write )

buffering, Set the buffer ;encoding, In general use utf8, Is not specified , The coding used depends on the platform ;......( I seldom use the back )

Read the entire file at once

file = './test.txt'# Specify the file path and file
with open(file,encoding='gbk') as f:# keyword with Automatically close a file when it is no longer needed to access it , So no need close Close file .
    contents = f.read()# Method read() Read the entire contents of the file , Stored in a variable as a string contents in     
print(contents)

Read the file line by line

file = './test.txt'
with open(file) as f:
    for line in f:# Use for loop
        line = line.strip()#strip Remove the newline at the end of each line
        print(line)

Overwrite existing content and write to file

file = './test.txt'
with open(file,encoding='gbk') as f:
    contents = f.read()
with open("./test1.txt", 'w') as f:#'w' Overwrite existing file contents
    f.write(contents)

#test1.txt Chinese content

Append to file

file = './test.txt'
with open(file,encoding='gbk') as f:
    contents = f.read()
with open("./test1.txt", 'w') as f:#'w' Overwrite existing file contents
    f.write(contents)

test1.txt Chinese content , A line is appended at the end , Do not overwrite existing content .

Looking back

NLP Exploration and practice of class problem modeling scheme

Python Common encryption algorithms in crawlers !

2D Transformation 3D, Look at NVIDIA's AI“ new ” magic !

Get it done Python Several common data structures !

 Share
Point collection
A little bit of praise
Click to see 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved