当前位置:网站首页>Exception, import package and file operation
Exception, import package and file operation
2022-07-24 23:55:00 【Nanlu seventeen】
● In program development , If the execution of some code cannot be determined to be correct , Can increase try( Try ) To catch exceptions
● The simplest syntax format to catch exceptions :
try: Code to try to execute
except: Wrong handling
●try Try , Write the code below to try , Code that is not sure whether it can execute normally
●except If not , Write the failed code below
try:
# Prompt for a number
num = int(input(" Please enter an integer :"))
except:
print(" Please enter the correct number :")
Capture the error : Catch exceptions according to the error type , Catch unknown error
# Full catch exception
try:
num = int(input(" Please enter an integer :"))
result = 8 / num
print(result)
# Catch exceptions according to the error type
except ZeroDivisionError:
print(" The denominator cannot be 0, Please re-enter :")
# except ValueError:
# print(" Denominator is not a number , Please re-enter :")
# Catch unknown error
except Exception as result:
print(" An unknown error occurred %s" % result)
else:
# Code that will be executed only when there are no exceptions
print(" The input form is correct !")
finally:
# Code that will execute whether there is an exception or not
print(" Code that will execute whether there is an exception or not ")
Transitivity of exceptions
● In development , Exception capture can be added to the main function
● Other functions that are called in the main function , As long as there is an exception , Will be passed to the exception capture of the main function
● So you don't have to be in the code , Add a lot of exception catching , Keep the code clean
def demo1():
return int(input(" Input integer :"))
def demo2():
return demo1()
# Take advantage of the transitivity of exceptions , Catch exception in main program
try:
print(demo2())
except Exception as result:
print(" Unknown error %s" % result)
Throw an exception
def input_password():
password = input(" Please input a password :")
if len(password) >= 8:
return password
print(" Throw an exception ")
# Create exception object , You can use the error message string as an argument
ex = Exception(" Insufficient password length ")
# Throw an exception
raise ex
try:
print(input_password())
except Exception as result:
print(result)
from ...import Local import
# Global variables
# hm_ Test module 1
title = " modular 1"
# function
def say_hello():
print(" I am a %s " % title)
# class
class Dog(object):
pass
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
title = " modular 2"
# hm_ Test module 2
def say_hello():
print(" I am a %s " % title)
class Cat(object):
pass
¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥¥
from hm_ Test module 1 import Dog
from hm_ Test module 2 import say_hello
say_hello()
wangcai = Dog()
print(wangcai)
If two modules , There is a function with the same name , Then the function of the post import module , The function imported first will be overwritten
● When developing import The code should be written at the top of the code , It's easier to detect conflicts in time
● Once a conflict is found , have access to as Keyword to give an alias to one of the tools
__name__ attribute
●__name__ Properties can do , The code of the test module is run only under test , When imported, it will not be executed !
●__name__ yes Python A built-in property of , Records a string
● If it is imported by other files ,__name__ Namely Module name
● If it is the program currently executing __name__ yes __main__
package
● A package is a special directory that contains multiple modules
● There is a special file in the directory init_ .py
● The package name is named in the same way as the variable name , Lowercase letters + mouth
benefits
● Use import The package name can import all modules in the package at one time
● To use the modules in the package externally , Need to be in init_ . py Specify the list of modules provided to the outside world
init.py
from . import send_passage
from . import receive_message
send_passage.py
def send(num):
print(" Sending file ..%s"%num)
receive_message.py
def receive():
return " This is from 100 The SMS "
hm_ Import package
import hm_message
hm_message.send_passage.send("hello")
txt = hm_message.receive_message.receive()
print(txt)
result :
Sending file ..hello
This is from 100 The SMS Make module compressed package
1. establish setup.py
2. Building blocks
The basic operation of the file
Open file
read 、 Writing documents ( read : Read the contents of the file into memory , Write : Write the contents of memory to a file )
Close file

open The function is responsible for opening the file , And return the file object
read/write/close All three methods need to be called through a file object
open The first argument to the function is the name of the file to open ( File names are case sensitive ). If the file exists , Returns the file operation object . If the file doesn't exist , It throws an exception
read Method can read in and return all the contents of the file at once
close Method is responsible for closing the file
If you forget to close the file , It will cause system resource consumption , And it will affect subsequent access to files · Be careful : After method execution , Will move the file pointer to the end of the file
#1 Open a file name ( You need to pay attention to case )
file = open("README")
# 2, Read file contents
text = file.read()
print(text)
# 3, close
file.close()
open Function does not edit the access method , The default is read-only , Don't write

readline Method
You can read one line at a time , After method execution , Will move the file pointer to the next line , Ready to read again
# Open file
file = open.("README")
while True:
And real :
# Read a line
text = file.readline()
# Judge whether the content is read
if not text:
break
# There is already at the end of each read line — individual ‘\’
print( text, end="")
First close file
file.close( )
File replication
Small file copy
Open an existing file , Read the complete content , And write to another file
#1, open
file_read = open( "README")
file_write = open( "REAMDE[ Copy ]","w"")
#2. read 、 Write
text = file_read.read()
file_write.write(text)
#3. close
file_read.close()
file_write.close()
Big file replication
Open an existing file , Read line by line , And write to another file in sequence m
#1, open
file_read = open( "README")
file_write = open( "REAMDE[ Copy ]","w"")
#2. read 、 Write
while True:
text = file_read.readline()
if not text:
break
file_write.write(text)
#3. close
file_read.close()
file_write.close()
file / Common directory management operations
Import OS modular

file = open(r"a.txt", "w", encoding='utf-8')
text = [" Cage osprey \n"," In the river of continent "]
# write() Write string to file ,,
# writelines Write a list of strings to a file , Do not add line breaks
# file.write(text)
file.writelines(text)
file.close()
with keyword
Context resources can be managed automatically , Jump out for whatever reason with block , Can ensure that the file is closed correctly , And it can automatically restore the scene when entering the code block after the code block is executed .
file= ["123\n","456"]
with open(r"b.txt","w") as file1:
file1.writelines(file)
边栏推荐
- How to make five kinds of data structures in redis
- 2022 最 NB 的 JVM 基础到调优笔记, 吃透阿里 P6 小 case
- 2. Load test
- Financial products can reach 6%. I want to open an account to buy financial products
- salesforce零基础学习(一百一十六)workflow -> flow浅谈
- codeforces round #805 ABCDEFG
- 给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享
- Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
- How to speculate on the Internet? Is it safe to speculate on mobile phones
- 代码覆盖率
猜你喜欢

芯片的功耗

Can Baidu network disk yundetectservice.exe be disabled and closed

指针与数组

QT learning - using database singleton to complete login matching + registration function

Multithreading & high concurrency (the latest in the whole network: interview questions + map + Notes) the interviewer is calm

Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK

Upgrade the jdbc driver to version 8.0.28 and connect to the pit record of MySQL

1、 MFC introduction

VGA display based on FPGA

Qt学习-利用数据库单例完成 登录匹配 + 注册 功能实现
随机推荐
Power consumption of chip
Regular expression learning
谢振东:公共交通行业数字化转型升级的探索与实践
Excel文件处理工具类(基于EasyExcel)
Technical operation
See project code Note 1
Coding builds an image, inherits the self built basic image, and reports an error unauthorized: invalid credential Please confirm that you have entered the correct user name and password.
Bug summary
Vite3.0 has been released, can you still roll it (list of new features)
cloud chart
1、 MFC introduction
Convex optimization Basics
Excel file processing tool class (based on easyexcel)
Advanced function of postman
Be an artistic test / development programmer and slowly change yourself
[nuxt 3] (x) runtime configuration
JS ------ Chapter II JS logic control
痞子衡嵌入式:MCUXpresso IDE下将源码制作成Lib库方法及其与IAR,MDK差异
Notes of Teacher Li Hongyi's 2020 in-depth learning series 5
ROS manipulator movelt learning notes 3 | kinect360 camera (V1) related configuration