Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of Python persistent storage and exception handling

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "what is the method of Python permanent storage and exception handling". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Permanent storage of Python (pickle module)

Stored as a binary sequence

Storage: pickling

Reading: unpickling

Permanently store a list

> import pickle

> my_list = [123 another list' 3.14159, ['Chinese]]

> pickle_file = open ('E:\ hyx02\ Python Learning\ my_list.pkl','wb')

> pickle.dump (my_list,pickle_file)

> pickle_file.close

You can write anything with a suffix in my_list.pkl.

The dump () method above:

Pickle.dump (obj, file, [, protocol])

Serialize the object and save the object obj to the file file. The parameter protocol is serialized, and the default is 0 (ASCII protocol, which means serialized as text), and the values of protocol can also be 1 and 2 (1 and 2 means serialized in binary form. Where 1 is the old binary protocol; 2 is the new binary protocol. File represents the class file object saved to. File must have a write () interface. File can be a file opened with'w' or a StringIO object, or any object that can implement the write () interface.

Test the stored results just now:

> pickle_file = open ('E:\ hyx02\ Python Learning\ my_list.pkl','rb')

> my_list2 = pickle.load (pickle_file)

> print (my_list2)

[123,3.14159, 'China', [' another list']]

Rb in code: binary form

By the same token:

Permanently store a dictionary

We can use this method to turn the data into a packet.

For example, write a dictionary (information about many cities) as a package

> import pickle

> pickle_file=open ('E:\ hyx02\ Python Learning\ city_data.aaa','wb')

City= {'Beijing': abbreviated as "Beijing", known as Yanjing and Peiping in ancient times, is the capital, provincial administrative region, municipality directly under the Central Government, national central city and mega-city of the people's Republic of China.' }

> pickle.dump (city,pickle_file)

> > pickle_file.close ()

Then when it is called:

> import pickle

> pickle_file=open ('E:\ hyx02\ Python Learning\ city_data.aaa','rb')

> city2 = pickle.load (pickle_file)

> city2

{'Beijing': abbreviated as "Beijing", formerly known as Yanjing and Peiping, is the capital, provincial administrative region, municipality directly under the Central Government, national central city and mega-city of the people's Republic of China.' }

The procedure can be streamlined.

Exception handling of Python (Exception)

File_name = input ('Please enter the file name you want to open:')

F = open (file_name)

Print ('contents of the file are:')

For each_line in f:

Print (each_line)

Enter the wrong file name: throw the file exception FileNotFoundError not found

FileNotFoundError: [Errno 2] No such file or directory: 'aaa'

Common anomalies

AssertionError: assertion statement (assert) failed

> my_list = ['aaaaa']

> assert len (my_list) > 0

> > my_list.pop ()

'aaaaa'

> assert len (my_list) > 0

Traceback (most recent call last):

File "", line 1, in

Assert len (my_list) > 0

AssertionError

An AssertionError exception is thrown and assert is used as a checkpoint in the middle of the program

As shown below:

AttributeError: attempt to access unknown object properties

> my_list.aaa

Traceback (most recent call last):

File "", line 1, in

My_list.aaa

AttributeError: 'list' object has no attribute' aaa'

An AttributeError exception is thrown, as shown below:

IndexError: the index is out of range of the sequence

KeyError: Key that does not exist

> my_dict = {'one':1,'two':2,'three':3}

> my_dict ['fout']

Traceback (most recent call last):

File "", line 1, in

My_dict ['fout']

KeyError: 'fout'

A KeyError exception is thrown, as shown below:

# using the get () method will not throw an exception

NameError: accessing variables that do not exist

OSError: there are many exceptions generated by the operating system. For example, the original FileNotFoundError belongs to OSError.

OverflowError: numeric operations exceed the maximum limit, which is not common in Python

Syntax error of SyntaxError:Python

> > print 'aaa'

SyntaxError: Missing parentheses in call to 'print'. Did you mean print ('aaa')?

Throw a syntax error without parentheses and change it into the form of a function call

As shown below:

Which Zhengzhou abortion hospital has a good http://3g.zyfuke.com/?

TypeError: cannot be calculated, for example, operations between different types

ZeroDivisionError: divisor 0

Anomaly detection

Try_except statement

Try:

Detection range

Except Exception [as reason]:

Handling code after an exception (Exception) occurs

Example:

Try:

F = open ('xxx.txt')

Print (f.read ())

F.close ()

Except OSError as reason:

Print ('file error ~\ nThe reason for the error is:' + str (reason))

Except TypeError as reason:

Print ('type error ~\ nThe reason for the error is:' + str (reason))

The running result is as follows:

Try:

Sum = 1 +'1'

F = open ('xxx.txt')

Print (f.read ())

F.close ()

Except OSError as reason:

Print ('file error ~\ nThe reason for the error is:' + str (reason))

Except TypeError as reason:

Print ('type error ~\ nThe reason for the error is:' + str (reason))

The running result is as follows:

You can also merge writing:

Except (OSError,TypeError) as reason:

Print ('error ~\ nThe reason for the error is:' + str (reason))

However, the above try_except statement is not recommended, for example, the file is not closed due to program interruption, so there are: try-finally statement

Try-finally statement

Try:

Detection range

Except Exception [as reason]

Handling code after an exception (Exception) occurs

Finally:

Code that will be executed anyway

Example:

Try:

F = open ('xxx.txt')

Print (f.read ())

Sum = 1 +'1'

Except (OSError,TypeError) as reason:

Print ('error ~\ nThe reason for the error is:' + str (reason))

Finally:

F.close ()

Raise statement

> raise ZeroDivisionError ('exception with divisor 0')

Show the above explanation

This is the end of the content of "what are the methods of Python persistent storage and exception handling". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 246

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report